Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Apache Struts - From Novice To Professional (2006)

.pdf
Скачиваний:
56
Добавлен:
17.08.2013
Размер:
11.68 Mб
Скачать

About the Technical Reviewer

KUNAL MITTAL is a consultant specializing in Java technology, the J2EE platform, web services, and SOA technologies. He has coauthored and contributed to several books on these topics. Kunal is a director in the information technology group within the Domestic TV division of Sony Pictures Entertainment. In his spare time he does consulting gigs for startups in the SOA space and for large companies looking to implement an SOA initiative. You can contact Kunal through his

website at www.soaconsultant.com or at kunal@kunalmittal.com.

xx

Acknowledgments

Any book is the product of a team effort, and this book is certainly no exception. I’m especially grateful to Kunal Mittal, who besides technically reviewing this book, made many suggestions that significantly improved its readability and utility. I’d like to thank Julie Smith for being the perfect project manager—giving support when needed and making sure that everything ran on schedule with a minimum amount of fuss—and all this through email!

Liz Welch did a great job of adding professional polish to the text and I’d like to thank her for being a huge help during the copyediting stage. Of course, any remaining errors are entirely the fault of my spellchecker! I’d like to thank Katie Stence for her patience in accommodating my many final changes.

My sincere thanks to Steve Anglin, who also saw the need for this book and agreed to let me write it.

Finally, this book would not be possible without the support of my wife Lillian, who endured many months with an absent husband. My humble thanks to you, my dearest.

xxi

P A R T 1

■ ■ ■

Basic Struts

Struts grew out of a personal need (open source developers often call this scratching your own itch) to support the development of an application that I was responsible for...

I began the process of open sourcing this idea of a web application framework at the Apache Software Foundation. What happened next was nothing short of extraordinary— Struts quickly became the de facto standard web application architecture in the J2EE space (the number of significant Internet applications built with it is substantial, but is dwarfed by the number of intranet applications that use it), integrated into nearly all the major app servers and tools, supported by a rich ecosystem of knowledgeable professionals and skilled developers, backed by significant documentation in the form of books and articles, and the basis for a large user community centered around the Struts User mailing list...

—Craig McClanahan

C H A P T E R 1

■ ■ ■

Introduction

This book describes a web application framework called Apache Struts, with which you can easily build robust, maintainable web applications. Now, the three italicized adjectives aren’t just hype:

Simplicity: Struts is relatively easy to pick up and use effectively. You get a lot out of Struts for the effort you put in to learn it.

Robustness: Struts provides much of the infrastructure you need to create webapps. You can rely on this tested body of code built on solid design principles, instead of having to come up with solutions of your own.

Maintainability: Struts is built around the Model-View-Controller (MVC) design pattern, which promotes separation between various portions of your webapp. This goes a long way to making your code maintainable.

Besides this, Struts has a huge user base and is a vital component in many Java-based enterprise web application solutions. It’s here to stay for some time to come.

Just to make sure we’re all on the same page, it might be helpful to understand what a web application is.

What Is a Web Application?

In this book, the term web application, or webapp, refers to any application whose user interface is hosted on a web browser. It is useful to think of webapps as falling somewhere on a continuum (see Figure 1-1). At one end of this continuum are webapps that deliver static content. Most websites are an example of this. On the other extreme are webapps that behave just like ordinary desktop applications. Struts is useful in building webapps on this right half of the continuum.

3

4

C H A P T E R 1 I N T R O D U C T I O N

Figure 1-1. The continuum of web application frameworks

So, if you’re planning to build a webapp requiring little or no user input or input validation, no data access, no complex business rules, or no need for internationalization, you probably don’t have to use Struts. If some or all of these are necessary, then your application would definitely benefit from using Struts.

Note I hope Figure 1-1 isn’t cause for confusion. There are many dimensions on which to place a particular framework (ease of use, support for a specific feature, cost, platform independence, etc.), and Figure 1-1 places the technologies on just one dimension.

I should warn you that the extreme right half of the continuum is not something Struts fully addresses either. Emerging technologies like JavaServer Faces (JSF) and Ajax (Asynchronous JavaScript and XML) attempt to address this deficiency.

Similarly, some web applications might require a mix of technologies to work, with Struts as a basic ingredient. The use of Enterprise JavaBeans (EJBs) for processing of business logic, or a template engine like Velocity to process text, are examples. In most cases, though, plain ol’ Struts will do the job.

In the course of this book, I’ll give you an overview of a number of technologies that work with Struts, among them Torque, Hibernate (in Appendix A), and JSF (which I’ll cover in detail in Chapter 18, along with Shale).

What Struts Can Do for You

Craig McClanahan created Struts because he was asked to port a U.S.-centric application to Europe. He had to give the application a web interface as well as allow it to be easily translated to four European languages (for this and other interesting bits, see Craig’s blog in “Useful Links” at the end of this chapter). So, needless to say, internationalization is something that Struts makes particularly easy to do. But Struts has much to offer beyond this.

Struts provides an extensive infrastructure for things like user input validation, error handling and reporting, and flow control, all of which are the bread and butter of building webapps. In my experience, about 30–50 percent of the time (and 100 percent of the tedium)

C H A P T E R 1 I N T R O D U C T I O N

5

used to build webapps revolves around these activities, so trimming it down substantially is a Very Good Thing Indeed.

Struts allows people with different skill sets—web designers, system analysts, system engineers, database engineers—to work in parallel. Struts does this by enforcing a “separation of concerns”: pieces of code that do different things are bundled separately and given standardized ways of communicating between themselves. This way, people can maintain or work on some parts of the webapp without having to worry too much about other parts. Can you see why?

Even if you’re a lone developer, Struts’ enforcement of a separation of concerns translates into modularized and therefore more maintainable code. Although this might sound like something you’ve always been doing in Java, Struts helps you do it across a smorgasbord of languages—Java, JSP, JavaScript, and SQL.

Struts does all this and is easy to learn, which certainly contributes to its popularity. There are, in fact, other web application frameworks, both open source and proprietary, but Struts has seen explosive growth over competing frameworks and now has a very large user base. So, if you’re ever stuck with a sticky Struts problem, you have ready access to a very large body of knowledge on the Internet.

About You

In writing this book, I’ve been presumptuous enough to make a few assumptions about your programming background. In particular, I’ve assumed that you have

No experience with servlets: If you have worked with servlets, then you have an advantage, but not much, since Struts does an admirable job of hiding most of the underlying servlet infrastructure.

Some experience with JSP: If you’ve only used ASP or PHP, not to worry; you should be able to pick up JSP essentials as the book progresses.

A working knowledge of Java: You don’t have to be a Java expert, but a sound knowledge of Java (1.4) basics is absolutely essential. If you can’t tell when to use a Reader and when to use an InputStream, you might find this book difficult to follow.

How to Read This Book

A friend of mine once compared programming to carpentry. I couldn’t agree more. Perhaps the only way to acquire new skills in either discipline is by application to nontrivial projects. Would you buy furniture built by someone who “learned” carpentry through correspondence?

6 C H A P T E R 1 I N T R O D U C T I O N

In the same spirit, this book takes a very hands-on approach in teaching you Struts. The lab sessions and exercises are an integral part of the book.

Note I can’t overemphasize this: You won’t learn a thing from this book if you don’t attempt the labs!

Having said that, I’ve tried to make the lab sessions challenging and interesting, but not overly complicated. Past the first few preliminary chapters, subsequent lab sessions involve building a nontrivial, real-life data entry and display application. I hope you enjoy seeing the final product emerge as you progress.

Every lab session has solutions, which have been carefully checked and independently reviewed, and which can be found in the Source Code section of the Apress website (http://www.apress.com). Questions raised in either the lab sessions or in the main text are in Appendix D.

There are two parts to this book, and each part ends with “review” labs, to help you solidify what you’ve learned.

The first part of the book covers Struts basics, as well as JSP and Servlet prerequisites. The second part of the book covers the more “advanced” portions of Struts like Tiles, the Validator framework, and how to build your own plug-ins, among other things. We’ll also study JSF and Struts Shale in the latter half of the book.

Useful Links

You’ll find the Apache Struts website at http://struts.apache.org.

Ted Husted’s website, http://husted.com/struts, contains many nuggets on Struts best practices.

The ServerSide, www.theserverside.com: has useful articles and discussions on Struts.

You’ll find Craig McClanahan’s blog at http://blogs.sun.com/roller/page/ craigmcc.

Spring is another web application framework; learn about it at www. springframework.org.

Pro Jakarta Struts, from Apress, is now in its second edition: http://www.apress. com/book/bookDisplay.html?bID=228.

Also check out Foundations of Ajax (http://www.apress.com/book/bookDisplay. html?bID=10042) and Pro Jakarta Velocity:From Professional to Expert (http:// www.apress.com/book/bookDisplay.html?bID=347), both from Apress.

C H A P T E R 2

■ ■ ■

Servlet and JSP Review

Struts is built on top of servlet technology, which is a basic infrastructure for building webapps with the Java platform.

This technology is really a specification laid out by Sun, detailing the behavior of a program called a servlet container. A servlet container takes care of parsing HTTP requests, managing sessions, and compiling JavaServer Pages (JSPs), among other things.

Servlets are Java classes you write in order to handle HTTP requests and responses. These classes are usually subclasses of HttpServlet, which has many convenience functions to help your servlet subclasses do their job.

Anyone can implement Sun’s Servlet specification, and in fact, there are many servlet containers available. Popular ones include WebLogic from IBM and the freely available, open source Tomcat from the Apache Software Foundation (ASF).

One of the beauties of Struts is that although it is dependent on servlet technology, you can develop Struts applications with having to know much about servlets! This chapter will equip you with everything you need to know about servlets for the journey ahead.

The first thing you need to do is install a servlet container on your machine.

Lab 2: Installing Tomcat

In this lab session, you’ll install the Tomcat servlet container on your PC. Be sure to finish this lab because you will be using Tomcat in subsequent chapters. Complete the following:

1.Choose a convenient location on your hard drive on which to perform the installation. Let’s call this the INSTALL directory. For example, you might want to use C:\Tomcat\ as an INSTALL directory.

2.From the Source Code section of the Apress website, found at http://www. apress.com, copy the file jakarta-tomcat-5.0.28.zip to the INSTALL directory.

7