Preface

In just a few short years, Struts (now officially called Apache Struts) has grown from a simple idea hatched in Craig McClanahan’s head into the most popular framework for building Java©-based web applications. There are other excellent Java-based web application frameworks available; many are newer than Struts, and most have benefited from lessons learned by the Struts users and developers. However, none of these frameworks offer the broad-range of features and functionality for which Struts is known.

Just as important, the Struts community—one of the largest in the world of open source development—actively supports fellow Struts users and drives Struts development. The struts-user mailing list often receives upwards of one hundred messages a day. Struts novices, experienced Struts users, and Struts committers are all active on this list. It has become an open, tolerant community in which the precept of knowledge sharing thrives in a congenial and refreshingly humorous environment. It’s with that attitude that I have written this book.

As developers, we latch onto tools, patterns, and software that works for us. Once we find a certain way of solving a problem, we tend to stick with that solution. We are naturally wary of new approaches to the same problem. It goes back to the old saying, “If it ain’t broke, don’t fix it.”

For a Struts developer, staying with the comfortable and familiar techniques will get you by, but you’ll be missing out on many innovative, creative, and entertaining ways of working with Struts. My aim with this book is to take away some of that anxiety when it comes to trying a new way of solving what may be an old problem.

The topics covered in these pages include:

  • Tools and techniques for developing a Struts application

  • Configuring your Struts application

  • Creating your user interface with the tag libraries

  • Working with Struts actions and action forms

  • Validating input and handling errors

  • Integrating Struts with your business model

  • Applying security to your application

  • Internationalization

  • Testing and debugging

  • Using Tiles and other presentation approaches

Audience

You will find this book most useful if you have some experience with Struts. If this isn’t the case, then you should first read Programming Jakarta Struts by Chuck Cavaness (O’Reilly).

Even if you consider yourself an advanced Struts user, you will find a great deal of useful information within these pages. This book covers the new features of Struts 1.2, as well as new ways of integrating Struts with emerging technologies, such as Java Server Faces and the Spring Framework. You will find that many of the solutions leverage Struts extensibility in ways that you may not have used or considered.

Knowledge of Java and JavaServer Pages technology is a prerequisite for any reader of this book. You will find it beneficial, though not required, to be familiar with the JSP (JavaServer Pages) Standard Tag Library (JSTL). JSTL allows you to write cleaner, more functional JSP pages than ever before.

Scope and Organization

Shortly after I started on the real meat of the recipes I ran into a dilemma. Do I focus on only those issues related directly to Struts? More importantly, should the Solutions only use technology available with Struts? I quickly realized that considering solutions that used Struts exclusively would be a disservice to the developer. Struts overlays and intersects with many other technologies from HTML to JSP to XML. I wanted the recipes to reflect this synergy as well.

Within the pages of this book you will find solutions that use tools and technologies not provided by Struts, such as the use of the JSTL. This ability to plug-and-play using external software tools and libraries demonstrates Struts’s flexibility and robustness. If you prefer to use JSTL over the Struts tags, then do it! Struts integrates just fine with JSTL, and I present many recipes that help you along. If you need to display tabular data with sorting and paging, you can roll your own solution or use a third-party library. This book will show you how to use both approaches.

Almost all of the solutions, which use third-party libraries, leverage open source software. Open source software has really come of age in the last few years. Though open source solutions are traditionally linked with bleeding-edge dot-com’ers, it’s been my experience that corporate IT shops are now seriously considering and using open source technology alongside traditional vendor offerings.

This environment empowers all developers. Through these freely available tools and libraries, you can easily set up—on your desktop computer no less—an environment capable of developing and testing enterprise-caliber J2EE applications. With the proliferation of high-speed Internet access, developing Java-based web applications has never been easier.

Sounds easy, right? If you’re like me, you are overwhelmed with so many choices. It’s hard to choose the right solution for the problem at hand. The recipes in this book help with this problem. I give you solutions that let you judge whether a particular tool or technique is well-suited to your situation. Instead of spending hours researching possible solutions, in 10 minutes you can solve your problem. Here’s the breakdown, chapter by chapter:

Chapter 1, Getting Started: Enabling Struts Development

This first chapter describes how to download Struts and deploy the sample applications. I’ll show you what’s involved in upgrading your application to the latest Struts Version. I will cover some advanced topics, presenting ways you can be more productive as a developer using tools like Ant and XDoclet.

Chapter 2, Configuring Struts Applications

Chapter 2 presents recipes illustrating the myriad of ways you can configure, organize, initialize, and architect your Struts application to suit your needs. I will show you how to separate your development into manageable groups using multiple configuration files. You will see how to set up Struts plug-ins, modules, and message resources.

Chapter 3, User Interface

Figuring out how to present data can be just as important as how to acquire data in the first place. This chapter delves into the world of the Struts tag libraries and focuses on creating robust pages that can adapt as the underlying model changes. Topics in this chapter include using indexed properties, incorporating the JSTL, working with date fields, and taking advantage of dynamically generated JavaScript.

Chapter 4, Tables, Sorting, and Grouping

This chapter is fairly straightforward and focuses primarily on using HTML tables for display of tabular data.

Chapter 5, Processing Forms

Struts uses action forms to move data from the view to the controller and back. Chapter 5 shows you how to be productive with action forms including the use of dynamic action forms. I’ll look at some different ways of mapping action forms to business objects.

Chapter 6, Leveraging Actions

Struts actions represent the integration point between the view and the model. Actions hook into your applications business logic and drive functionality. In Chapter 6, you’ll see how to get the most out of your actions. You’ll learn how to take advantage of Struts pre-defined actions, simplifying and improving your application.

Chapter 7, Execution Control

This chapter addresses problems related to managing your application’s life cycle and handling different navigation requirements. The solutions show you how to use Struts plug-ins, servlet context, and session listeners. The chapter covers creating wizard-style interfaces, preventing double-form submission, and handling file uploads.

Chapter 8, Input Validation

A good web application verifies that entered data is valid before it sends that data to the business layer. Chapter 8 shows you how you can build validation into your application using the Struts Validator. Even when your data is valid, your application may still need to handle unexpected errors.

Chapter 9, Exception and Error Handling

Chapter 9 shows you how you can handle errors and exceptional conditions in a predictable manner.

Chapter 10, Connecting to the Data

Struts doesn’t provide the model for your application; rather, it provides hooks that allow you to integrate your model with the controller. I show you a number of popular ways that you can integrate Struts to the model in this chapter. In particular, I’ll explore integrating Struts with the persistent frameworks like iBATIS and Hibernate. I’ll show you some useful patterns for abstracting data access behind service interfaces. I’ll show you how you can integrate Struts with the Spring inversion-of-control (IOC) framework.

Chapter 11, Security

Most web applications have some requirements for security. These can vary widely from simple password authentication to complex integration with back-end directory services. In this chapter, I consider those security issues that are particularly applicable at the web tier. I’ll show you various techniques for securing your application from simple base Actions to container-managed security and beyond.

Chapter 12, Internationalization

From the outset, the ability to localize a web application for a particular spoken language and geographic region has been a core feature of Struts. In Chapter 12, I’ll show you how to maximize those features to address problems related to supporting multiple languages.

Chapter 13, Testing and Debugging

If you can’t test your application, you are bound to become overwhelmed with defects when you release your application to production. This chapter shows you a number of techniques for solving the tricky issues of testing and debugging J2EE applications. With the recipes in this chapter, you will be well-equipped to find defects before your application gets to production or the QA team.

Chapter 14, Tiles and Other Presentation Approaches

Struts was designed from the beginning with extensibility and customization as first-class features. This final chapter shows how you can leverage this ability with the presentation side of your application. This chapter shows you how to get started using Tiles. I’ll investigate an alternative approach to layout-management using SiteMesh. This chapter closes with recipes that show you how to integrate Struts with alternative presentation approaches such as JavaServer Faces, Velocity, and XSLT.

It’s not possible to cover every problem that you may encounter in development of a Struts application. Keep in mind that the solution is not necessarily meant to be taken in isolation. In fact, you may find that your problem is solved by combining several solutions together. If you still can’t resolve your problem, please let me know. More importantly, take your problem to the struts-user mailing; the Struts community is always willing to help.

Assumptions This Book Makes

This book assumes that you have some experience with Struts. It’s expected that you know how to build and deploy a J2EE web application. A servlet container like Tomcat or Resin is required to run the sample web applications. Full-blown J2EE application server like JBoss, Weblogic, and WebSphere will work fine though they are not required as none of the solutions utilize Enterprise JavaBeans©.

The majority of the sample applications were built and tested on a Windows XP machine running Tomcat 5.0.29. I primarily used Firefox (Version 1.0) as my browser.

Conventions Used in This Book

In addition to the normal typographical conventions of an O’Reilly book, Struts has a large number of confusing terms. I’ve reduced that confusion by adopting some programming conventions throughout the book.

Programming Conventions

Throughout the book, I use the following conventions regarding Struts actions:

action

Refers to the concept of an action

Action

Refers to the Java class

action

Refers to the <action> element in an XML file

Java classes and interfaces are always written in constant width with the first character in upper case. When I refer to a particular method of a class, I use the convention of ClassName.methodName( ). This does not mean that the method is static; instead, it is just a convenient means of reference.

When XML, HTML, and JSP elements and tags are referenced in text, the angle braces are omitted and appear like forward, td, and bean:write. When I refer to a Struts configuration file, I use the canonical name, struts-config.xml, though you can give these files any name that you prefer. Similarly, the Validator and Tiles configuration files are referred the validation.xml and tiles-defs.xml canonical names.

Typographical Conventions

The following typographical conventions are used in this book:

Plain text

Indicates menu titles, menu options, menu buttons, and keyboard accelerators (such as Alt and Ctrl).

Italic

Indicates new terms, URLs, email addresses, filenames, file extensions, pathnames, directories, and Unix utilities.

Constant width

Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, and the output from commands.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values.

Tip

This icon signifies a tip, suggestion, or general note.

Warning

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Jakarta Struts Cookbook by Bill Siggelkow. Copyright 2005 O’Reilly Media, Inc., 0-596-00771-X.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Comments and Questions

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)

O’Reilly maintains a web page for this book that lists errata, examples, and any additional information. You can access this page at:

http://www.oreilly.com/catalog/jakartastrutsckbk

To comment or ask technical questions about this book, send email to:

For more information about O’Reilly books, conferences, Resource Centers, and the O’Reilly Network, see O’Reilly’s web site at:

http://www.oreilly.com

Safari Enabled

image with no caption

When you see a Safari® Enabled icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf.

Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com.

Acknowledgments

Writing this book has been a demanding and rewarding experience. I have learned a great deal in the process and I am thankful to many of my friends, family, and peers. First, I want to thank the folks at O’Reilly and especially my editor, Brett McLaughlin. His patience and encouragement helped me make it through some worrisome times. Most of all, Brett emphasized quality above anything else.

I would like to thank my family, as well. As a part-time writer, finding time to write, research, and code was not always easy. I sincerely appreciate the sacrifices that my wife, Debbie, and my boys, Kyle and Cameron, made while I worked on the book. Their encouragement and patience was a blessing. I want to thank my brother, Ed, and my Mom and Dad. Mom, I know you may not know exactly what a “Strut” is, but thanks for always being interested.

This book would not have been possible without the prior work of Chuck Cavaness and Brian Keeton. Chuck’s book Programming Jakarta Struts (O’Reilly), a staple of Struts literature, laid the groundwork for this book. Chuck and Brian also wrote the preliminary set of recipes for this book which really helped me get started.

Finally, big thanks go out to my technical editors: Ted Husted, James Mitchell, and James Holmes. Ted can rightly be called a Struts legend and I was honored to have him as a reviewer. He provided a historical perspective which helped me explain and understand the evolution of Struts. As far as James and James go, these fellows are not just my respected colleagues; they are my good friends. I appreciate their time, effort, and encouragement throughout the entire process. In particular, I want to thank James Mitchell for recommending me as a writer and helping out with the initial chapter outlines. I want to thank James Holmes for allowing me to contribute to his book, Struts: The Complete Reference (McGraw-Hill/Osborne).

Finally, this book would not have been possible without the Struts community of developers. Many of the recipes in this book are based on the common—and not so common—questions, answers, and discussions from the struts-user mailing list. I did my best to give credit where a particular solution was provided by a specific developer. However, I may have missed giving credit where it is due. Please accept my apologies where this has occurred, and let me know of any gross omissions.

I would like to thank Craig McClanahan for developing Struts and helping me with the Struts-Faces recipe. Jonathan Freeman and Stephanie Peretti supplanted my lack of graphic and Spanish-speaking skills. Niall Pemberton and Hubert Rabago provided excellent feedback on a number of recipes. I would like to thank Rick Reumann for the excellent tutorials on his “Struttin’ with Struts” web site. Finally, thanks to my good friend, Anuj Soni, whose friendship, advice, and encouragement has been a blessing over the years.

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.