Learning Jakarta Struts 1.2: a concise and practical tutorial

By Stephan Wiesner
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to Struts

About this book

Jakarta Struts is an Open Source Java framework for developing web applications. By cleanly separating logic and presentation, Struts makes applications more manageable and maintainable.
Since its donation to the Apache Foundation  in 2001, Struts has been rapidly accepted as the leading Java web application framework, and community support and development is well established.

Struts-based web sites are built from the ground up to be easily modifiable and maintainable, and internationalization and flexibility of design are deeply rooted. Struts uses the Model-View-Controller design pattern to enforce a strict separation between processing logic and presentation logic, and enables efficient object re-use.

The book is written as a structured tutorial, with each chapter building on the last. The book begins by introducing the architecture of a Struts application in terms of the Model-View-Controller pattern. Having explained how to install Jakarta and Struts, the book then goes straight into an initial implementation of the book store. The well structured code of the book store application is explained and related simply to the architectural issues.

Custom Actions, internationalization and the possibilities offered by Taglibs are covered early to illustrate the power and flexibility inherent in the framework. The bookstore application is then enhanced in functionality and quality through the addition of logging and configuration data, and well-crafted forms. At each stage of enhancement, the design issues are laid out succinctly, then the practical implementation explained clearly. This combination of theory and practical example lays a solid understanding of both the principles and the practice of building Struts applications.

Publication date:
August 2005
Publisher
Packt
Pages
220
ISBN
9781904811541

 

Chapter 1. Introduction to Struts

This chapter is intended as a fast-track introduction to Struts for those of you who are new to it. If you already have Struts experience, you may wish to skip this chapter and proceed directly to Chapter 2, where we get started on building the sample application. However, you may find this chapter a useful refresher and reference while you work.

1.1 The Apache Jakarta Project

The most popular product produced under the aegis of the Apache Software Foundation ( http://www.apache.org) is without doubt the Apache HTTP web server, which holds about 70% market share. The Tomcat web server, a part of the Foundation’s Jakarta project that can be run either as a plug-in for Apache or standalone, is gaining similar popularity. Apache projects are grouped according to technologies they involve, and are themselves broken up into sub-projects. Jakarta really is the place to go for open-source Java projects, and it can be found at http://jakarta.apache.org. There are a couple of exceptions, notably Torque, a very useful object-oriented database mapping tool, that can be found under the Apache-DB project, although it is written in Java.

If you are not already familiar with Apache Jakarta, then it is strongly recommend that you take some time to browse around the site to get a general picture of the products under development. You’re sure to find something interesting, and you may well find some particularly useful tool.

For serious users of Apache products, the official mailing lists play a vital role. The archive for the mailings list can be found at http://marc.theaimsgroup.com/.

Subscribe to the lists now (follow the Mailing Lists link on the Jakarta home page) rather than waiting until you need to ask for help. That way, you can scan through the questions and responses first and get a feel for how it all works. One warning though: in a typical day, a hundred or more messages are exchanged. So it is advised that you to set your e-mail program to move them to a special folder that you can check at your leisure.

Note

Note that there is an archive of old questions. Netiquette dictates you should search that first in order to avoid making duplicate requests for help.

If there is one area where open source is wanting, it’s probably the documentation, which often is poor, out-dated, or both. The mailing lists help make up for this, and once you are used to them, you will find they mean you always have someone to ask if you are stuck.

Open source versus proprietary is a hotly contested battle, and we’ll see further advantages and disadvantages of both put forward by both camps. http://www.opensource.org/ is a good source for entry into this subject. If you would like to find out more about the philosophy behind open-source software, we highly recommend The Cathedral and The Bazaar, by Eric S. Raymond (O’Reilly, 1999 ISBN 1-56592-724-9).

 

1.1 The Apache Jakarta Project


The most popular product produced under the aegis of the Apache Software Foundation ( http://www.apache.org) is without doubt the Apache HTTP web server, which holds about 70% market share. The Tomcat web server, a part of the Foundation’s Jakarta project that can be run either as a plug-in for Apache or standalone, is gaining similar popularity. Apache projects are grouped according to technologies they involve, and are themselves broken up into sub-projects. Jakarta really is the place to go for open-source Java projects, and it can be found at http://jakarta.apache.org. There are a couple of exceptions, notably Torque, a very useful object-oriented database mapping tool, that can be found under the Apache-DB project, although it is written in Java.

If you are not already familiar with Apache Jakarta, then it is strongly recommend that you take some time to browse around the site to get a general picture of the products under development. You’re sure to find something interesting, and you may well find some particularly useful tool.

For serious users of Apache products, the official mailing lists play a vital role. The archive for the mailings list can be found at http://marc.theaimsgroup.com/.

Subscribe to the lists now (follow the Mailing Lists link on the Jakarta home page) rather than waiting until you need to ask for help. That way, you can scan through the questions and responses first and get a feel for how it all works. One warning though: in a typical day, a hundred or more messages are exchanged. So it is advised that you to set your e-mail program to move them to a special folder that you can check at your leisure.

Note

Note that there is an archive of old questions. Netiquette dictates you should search that first in order to avoid making duplicate requests for help.

If there is one area where open source is wanting, it’s probably the documentation, which often is poor, out-dated, or both. The mailing lists help make up for this, and once you are used to them, you will find they mean you always have someone to ask if you are stuck.

Open source versus proprietary is a hotly contested battle, and we’ll see further advantages and disadvantages of both put forward by both camps. http://www.opensource.org/ is a good source for entry into this subject. If you would like to find out more about the philosophy behind open-source software, we highly recommend The Cathedral and The Bazaar, by Eric S. Raymond (O’Reilly, 1999 ISBN 1-56592-724-9).

 

1.2 The Struts Project


"Welcome to Struts! The goal of this project is to provide an open source framework for building Java web applications."

The dictionary defines a "strut" as a structural support, and the definition extends well to Struts: it provides the basic framework upon which you can construct an application.

Struts was brought to life by Craig R. McClanahan in May 2000, who donated it to Apache, where it became a project under Jakarta. It has since become an Apache project in its own right. Version 1.0 was released in the summer of 2001, with the objective of creating a framework that cleanly separated logic and presentation, to make web applications more manageable and maintainable.

The benefits of Struts for creating well-designed web applications in Java led it to gain respect and acceptance quickly. The JSP Standard Tag Library (JSTL), which provides some of the same functionalities offered by Struts, can be seen as a direct reaction by Sun to the impact that Struts has had.

As Struts is provided under the Apache open-source license, everyone has full access to the source code, without charge and without having to pay royalties when Struts is used in a commercial product.

The developer has several choices when choosing the technology for a dynamic website (or web application). Languages such as ASP, PHP, and Java Server Pages allow sites to be quickly put together by providing additional tags and constructs that can be mixed in with HTML. In effect, the HTML tags (tables and so on) are usually used for formatting and presenting information to the user. Usually sites obtain information from the user through HTML forms, which must then be processed, and errors, if any, must be handled appropriately. Struts makes it easier and quicker to build and maintain powerful interactive websites by creating a framework that encapsulates the essentials of a web application’s structure.

This does not mean that the task is child’s play. There is a tendency for people who have developed small sites—perhaps during the course of a college or university degree—to become overconfident and overestimate their own ability. Rushing headlong into the development task to build a real-world web application that needs to handle large amounts of data and a number of users is much less likely to work. This may sometimes result in further development becoming almost impossible. Badly structured web applications become difficult to update with new functionality or styling, and common problems like form processing, error handling, and internationalization reappear in many different places. A framework such as Struts, where all these problems are already solved for you, represents a potentially huge jump in productivity. Also, the control of application flow for e-businesses—typically product display, selection (adding products to the cart), collection of order information, transaction completion—is easier with the central controller that Struts offers than with a number of loose, unconnected pages.

The main drawback of using a third-party framework like Struts is that you must spend extra time familiarizing yourself with it. This must be considered as a worthwhile investment, even though it is hard to measure the success of such investment, as is often the case in software development. For instance, Struts applications are very well structured and so it is essential that the basic principles of an application are set out early, and initial effort is put into the building of the base classes. So you may spend a week mastering Struts, in which time no effort is put into creating the web application, and this must be factored into your project schedule. Not every project leader or customer will recognize the usefulness of these activities.

 

1.3 The Struts Framework


This section explains the basic principles and concepts of Struts. A glossary is provided at the end of the book where the technical terms used in the text are explained.

Struts-based websites are built to be easily modifiable and maintainable, and the internationalization and flexibility of design is deeply rooted. A strict separation is enforced between processing logic and presentation logic (the Model and View in Struts parlance), which has a natural consequence of facilitating component reuse.

All the main configuration of a Struts web application is performed by struts‑config.xml. Here mappings can be defined between aliases and classes or between aliases and JSP pages. It is also here that the connections between Bean, Form, and Action classes are established. This centralization gives a better overview of the structure of an application, and also allows individual components of an application to be more easily modified. One big disadvantage is that any change requires a restart of the server; it is not possible to make changes at run time.

For just about every bean, there’s a Form class and an Action class. These determine how classes are filled, what values are valid, and what happens then. Struts can be a little pedantic with this structuring, but it does allow extensive support for user input, error handling, and database access. The problem here is that the separation of Model, View, and Controller becomes difficult to achieve. What belongs where? Database access in the Action class, for example, is easy and efficient, but these classes cannot be replaced with non-Struts code, as you will see later on.

Another increasingly important consideration for commercial websites is Internationalization. In Struts, this is achieved via central language files. The application.properties file can be easily extended to support new languages. The server will attempt to use the user’s preferred language; otherwise, the default language is adopted. The internationalization in Struts complies with the standard internationalization mechanisms of Java. The drawback is that errors in individual texts can cause run-time errors. Run-time errors are the first errors your clients will notice when your site goes live.

Being able to centrally define the validation that the Validator must perform and using its ability to decide upon JavaScript or server-side testing greatly simplifies building and maintaining robust forms for capturing user input. The price is that these central XML files can quickly become large and complex. In addition, the use of JavaScript leads to higher bandwidth usage because all possible pre-packaged JavaScript functions are included in the response.

If you have any experience of older style JSP programming, or even if you don’t, you may be wondering why it’s so important to keep Java code out of JSP pages as far as possible. These are the three most often cited reasons:

  • It enables a part of the developing team not to know any Java at all.

  • It assists in the separation of the processing and presentation logic layers.

  • It encourages developers to make reusable code.

 

1.4 Model Classes


Model classes appear frequently in this book. There are two different types of model classes. The first are JavaBeans, which represent the state of an object. These are simple

Java classes that define a number of private variables that are assigned a value by calling their set method, or the value is read using the variable’s get method.

The second type of class relates to the behavior of the application, that is, Business Logic classes. The actions provided by the beans are executed here. For example, the Customer object might work together with the Shopping Cart object to complete the task of placing an order.

Struts works in conjunction with JavaBeans to process forms. A typical example might be a Customer Bean, which is used in tandem with a set of forms to enable users to register.

Here are a few tips to make things easier for you:

Note

Always use Packages.

The servlet specifications demand it, and it is why older Tomcat 3 applications cannot be executed in later versions of Tomcat. You will really need to understand the principles of Java packages. It is better not to start working with servlets directly, but work on the foundation a bit more.

Note

Avoid naming your packages Model.

While a common practice, this naming conveys nothing about what the package contains. Do all classes exist here? Or only beans? It’s much better to use more descriptive names, especially for large-scale applications where the Model can be implemented by multiple Java packages.

Note

Install a Development Tool.

A good IDE, such as the Eclipse-based WebSphere Application Developer (WSAD), can help avoid many errors and increase your productivity tremendously. For example, the validity of your links can be checked automatically, Wizards can help in building classes, etc.

Eclipse 3.1 provides an add on that enables the editing of JSPs and the management of Tomcat (similar to WSAD 5.x). A tutorial for this can be found at http://www.eclipse.org/webtools/testtutorials/M2/tutorial1/wtp-tutorial-I.html.

 

1.5 Design Patterns


"Design patterns capture solutions that have developed and evolved over time. Hence they aren’t the designs people tend to generate initially. They reflect untold redesign and recoding as developers have struggled for greater reuse and flexibility in their software. Design patterns capture these solutions in a succinct and easily applied form."

[The Gang of Four]

We cannot go into detail on the subject of Design Patterns in this section, and we focus only the pattern that guided the design of Struts—the Model View Controller ( MVC).

Design Patterns devised by The Gang of Four (GOF) are solutions for commonly recurring design problems. They can be considered as recipes that may be applied to overcome complex problems. One of their objectives is to help create software that is easy to maintain. Furthermore, the nomenclature of Design Patterns makes discussions on software much simpler: "For this problem I will use the Singleton Design Pattern" is much less of a mouthful than "For this problem, I will write a class and ensure that this class has only one instance", which is what the Singleton Design Pattern entails.

Imagine you wish to become an expert at making, let’s say, tomato soup. If you ask ten different Master Chefs for their own recipe, you will get ten recipes, which are similar in some ways but different in others. It is true for creating software as well: there is no single design pattern that can make a master software architect out of a beginner.

There are many different ways to implement the various popular patterns and you can find many different studies of their effectiveness on the Internet. This can lead to misunderstanding and inconsistencies when different developers on a team are familiar with different interpretations of the same pattern.

 

1.6 The Model View Controller (MVC)


"MVC consists of three kinds of objects. The Model is the application object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input. Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse."

[The Gang Of Four]

The idea of separating an application into two layers—one concerned with presentation and the other concerned with processing logic—and orchestrating the two of them with a central controller is about twenty years old and time-tested.

The upshot for the developer is that the View portion is constructed using Java Server Pages (JSP) and should contain little or no Java at all. For the Controller, a central servlet provided by Struts is used, and Taglibs and beans implement the Logic portion.

To understand the principle, imagine an application with a web component (such as our shop) and a Swing-GUI for local users. Both the web and local portions have to accomplish very similar tasks but will have different appearances. Naturally, as the developer you want to do as little work as possible.

With MVC, you would choose to put every activity that is used by both (for example, database access) in the Model portion. The View portion would need to be different, using JSP pages for the web-accessible component and normal Java classes for the local client. The point is that while View components will need to be implemented twice, Model components can be used by both the web and the local components.

We will of course learn about the many possibilities of Struts as this book progresses, but for Swing application development, you would work with events and listeners.

JSP, introduced by Sun Microsystems, provides a nice way to combine HTML and Java. However, as discussed before, this leads to maintenance problems as well as hindering enhancements, and so now we have what is known as the Model 2 paradigm.

A big problem websites face is the fact that the protocol underpinning the Internet, HTTP, is stateless. This means that there is no built-in way for a web server to link different requests any user may make. It can simply react to each request independently. The classic-listener principle, as we know from Swing, does not work in this case.

Exercise 1

Read about the Observer Design Pattern and look into the observer and observable standard Java classes.

 

1.7 MVC versus Model 2


The Model 2 concept is usually brought up in relation to JSP and Struts. The concept was coined in the JSP specifications. Initially, only JSP was responsible for all the work (Model 1). But in time, developers realized that these JSP pages are hard to maintain and thus the Model 2 principle was conceived. In Model 2, the central controller servlet is responsible for the main control of the application. JavaBeans and Taglibs form the foundation, leaving JSP responsible for only the presentation layer. Later in the book, we put this approach to practice and apply the Struts solution shown in following figure:

Figure 1.1: Model 2

Figure 1.1 shows how the user (the client) accesses the central controller servlet via the URL requested by the browser. After that, the appropriate JSP pages, which use any required business classes from the Model, are accessed. The Model in turn uses any other required resources such as the database.

Note that access to the controller is implicit—the user does not notice anything different.

To configure an Action servlet, you use the<servlet> element within web.xml to define the servlet instance, which is then mapped by the<servlet-mapping> element. One of the child elements of<servlet> is<servlet-class>, which for an Action servlet must specify the class org.apache.struts.action.ActionServlet. The following fragment shows how the<servlet-mapping> element is used:

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

The<global-forwards> and<action-mappings> elements in struts-config.xml make sure the correct JSP pages or org.apache.struts.action classes are invoked. When the data on a form is submitted, it is validated and the form receives the required processing or else is displayed again with an error message. The Action classes can process the control flow further or invoke objects of other classes to process it.

An Action can do various things—such as adding a product to a shopping cart object stored in session—before passing control to further mappings. These mappings might refer to a JSP page, for instance, to display the shopping cart. Because each user has their own unique session, the page will always show their own particular products. The Action cannot itself have any knowledge of business logic. It is only responsible for delegating control and performing error handling.

Exercise 2

  1. 1. Trouble yourself to write a small Java GUI to store details of items such as books in a database. Aim to create base classes that can be reused to reduce your overall workload.

  2. 2. Plan how you would go about writing the software for an online shop so that it could be easily maintained and expanded. Also imagine that you have the listing for such an online shop, but the developer is not reachable, and there is almost no documentation. How would you get acquainted with the code? What would you need to know in order to implement a new function, "Show all old orders for a customer"?

  3. 3. Give a thought to which should be built first, the Model or the View. Or would you build both side-by-side? Think about why this is an important question to answer before the development task gets under way.

 

1.8 Controller Component: ActionServlet


The ActionServlet instance is not only the central control instance of your application but also responsible for the initialization and clean up of resources used. Initialization is performed based on the values specified in the configuration files.

For each request made to the controller, the process() method gets called, with the request and response objects passed in as the two parameters: HttpServletRequest and HttpServletResponse. This method determines which module should process the request and then invokes that module’s corresponding RequestProcessor.process() method, passing in the same request and response objects as parameters.

 

1.9 Design Guidelines for Action Classes


Here are some guidelines for building Action classes. Remember that you will be in a multi-threaded environment: only one instance of your class will be created and this instance will spawn threads to handle each request. The same is true of servlets, and the following guidelines apply equally to them.

  • Only use local variables: Do not use instance variables (apart from constants). Local variables are created on a stack that is assigned by your Java Virtual Machine for each request. When an action is handled by local methods, data must pass between them using parameters exclusively, and not through instance variables.

  • Conserve resources: Even though creating objects in session can seem like a quick way to solve problems, it can lead to scalability problems. For example, if you are using JDBC to connect to a backend database, and you store a separate connection for every user in session, your website could easily grind to a standstill if you experience a lot of traffic. For this particular problem, connection pooling is a preferred solution.

  • Don’t ignore error handling: Nothing diminishes confidence in a commercial site quicker than an ugly stack trace appearing when a customer tries to perform a transaction. Will the transaction be completed? What will happen to their data? Struts offers a variety of options to catch errors so that a more informative and readable error message can be displayed.

  • Avoid long and complex action classes: You should embed as little business logic as possible in your Action classes, to increase their maintainability, reusability, and readability. In fact, one of Struts’ own MailReader example makes this same mistake of burying business logic in the Action class. The documentation confesses: "[it] should be considered something of a bug in the design of the example, rather than an intrinsic feature of the Struts architecture, or an approach to be emulated."

 

1.10 Reflection, Introspection, and DynaBeans


The reflection mechanism allows Java code to process the bytecode resulting from the compilation process. It allows the developer to define and call the parameters from .class files, and is essential for many development tasks, such as creating an IDE.

Introspection is a special form of reflection and is used by the JavaBean API. Here the methods must follow a particular naming convention to determine how those methods may be called. For instance, say your JavaBean has a property called Name. Then you would need the property accessors to be named getName() and setName() (and not, say, nameSet()).

Struts uses introspection to fill a form according to the parameters in the request and to then call the JavaBeans. If you’d like to find out more about introspection, try the online Sun tutorial (http://java.sun.com/docs/books/tutorial/reflect/) on the subject.

Form processing is a task that occurs very frequently. Writing simple beans for validating these forms can be a repetitive task. Struts aims to fix this with DynaBeans packaged with the Jakarta Commons JAR file (http://jakarta.apache.org/commons/beanutils/). With the help of an XML descriptor, they can be configured dynamically at run time. Instead of defining one JavaBean for every form—that needs to be recompiled and the server restarted on every modification—the relevant properties are declared only once:

<form-bean name="loginForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="mail" type="java.lang.String" />
<form-property name="password" type="java.lang.String" />
</form-bean>

We’ll be using this simple example later. The mechanism doesn’t rely on the generation of JavaBeans, rather a map is created that has the required classes and their properties embedded in it. These can be extracted through introspection. If you do not initialize your objects implicitly, then numbers will start with the value zero, and other objects will be set to null.

 

1.11 Session


Even though HTTP is stateless by nature, there are several techniques to identify individual users.

The easiest is to include hidden fields within your HTML forms.

<form name="UserInformation">
<input type="hidden" name="name" value="Stephan Wiesner" />
</form>

Such fields do not appear in the browser display, but will be sent with the rest of the form data that the user has entered when he or she submits the form. Hidden form fields are far from ideal however: they result in extra data traffic and the user can see them anyway by choosing View Source in their browser. They are one way that malicious users can attempt to mount an attack on your web application. It is also possible for an unauthorized third party to view the data they contain by intercepting a user’s requests. This last problem can be eliminated with the use of SSL.

Cookies are another simple way of identifying users. They are very short text files stored on the user’s computer. While they are safe to use in updated browsers, their reputation is far from unblemished, and for that reason you can’t rely on all your users having them switched on.

Note

Give it a Thought!

For a particular project, an entire web interface based on cookies was created. Then a couple of e-mails were received from users complaining that the site didn’t work for them. The entire site was converted, which took several weeks, reasoning that for each user who complained, hundreds probably never bothered, and simply never came back.

The most elegant method is the use of a single session. Session is a Java object, much like Map, for storing other objects with a given name (or key). Each user is linked to their session either via a cookie or via URL-rewriting. You should always use the latter, because subsequent changes are cumbersome to perform. However, if your application will be deployed on a private intranet where the environment can be "dictated", using cookies might be acceptable. The servlet specification advises to store only serializable objects in session. You can, however, store other objects, but such objects will not be able to be restored in the event of a system failure. Servers such as WebSphere Application Server claim to be able to manage failures without losing such data, although you must be able to buffer the data. Another point to remember is that many servers can release session objects from storage as soon as they are buffered, allowing them to handle more users.

Note

Session length

Avoid overusing session; remember that every user will have his or her session on the server. There are projects where the developer allowed the session to grow to 40 MB. Naturally, as more and more users tried to access pages simultaneously, the demand on server memory increased very fast and quickly became unmanageable. Normally a session should be no more than one or two KB, but the maximum size depends on how many visitors you expect.

The following JSP code demonstrates how to store and retrieve items from session. It starts by storing a string value with setAttribute(), and a HashMap containing three further string values. The code then iterates through an enumeration displaying every session item in the browser, as well as writing it out to a file. Finally it displays the size of the session.

Listing 1.1: SessionStorage.jsp

<%@page import="java.io.*, java.util.*, javax.servlet.http.*"%>
<html>
<body>
<pre>
<%
out.println("Starting...");
session.setAttribute("username", "Stephan");
HashMap map = new HashMap();
map.put("one", "First");
map.put("two", "Second");
map.put("three", "Third");
session.setAttribute("map", map);
ObjectOutput output = null;
try
{
OutputStream file = new FileOutputStream( "test.ser" );
OutputStream buffer = new BufferedOutputStream( file );
output = new ObjectOutputStream( buffer );
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements())
{
String name = (String)e.nextElement();
Object o = session.getAttribute(name);
out.println(name + "=" + o);
output.writeObject(o);
}
output.close();
File f = new File("test.ser");
out.println("Size:" + f.length());
}
catch(IOException ex)
{
out.println("Error:" + ex);
}
%>
</pre>
</body>
</html>
 

1.12 Business Logic


In order to achieve maximum reusability, the business logic beans should be implemented as generally as possible, avoiding specifics of any particular web application. If you find yourself importing the javax.servlet.* classes, stop and rethink your design. You should try to get your Action classes to call the Property methods, rather than working directly with servlet methods.

Note that depending on the complexity of the application, the business logic will be implemented either in regular JavaBeans or in Java Enterprise Beans. This does not make any difference for Struts.

 

1.13 Threads


The thread safety of an application is one of those things that developers like to sweep under the carpet, and hope it’ll be OK. However, this is a mistake and learning to ensure that your classes are thread safe will pay great dividends in the long run. Thread safety is something that won’t necessarily present problems in the ad hoc tests a developer might perform on their code, when everything might function smoothly. Once two customers perform the same action simultaneously, thread safety immediately becomes an issue. For example, customer A orders some books that customer B ordered a split second before, and suddenly customer B finds their shopping cart empty. Such mistakes are hard to trace, because they are very hard to reproduce.

Java offers good protection from concurrency, although it involves many details that can make one’s life difficult. Unsynchronized access over the Web makes the problem worse, particularly during testing.

The easy solution is to use tools such as JMeter, which can simulate heavy traffic. Virtual users access the site, placing load on the server and then the manual tests are executed. This increases the chances that such errors will be caught.

Struts is itself thread safe as you might expect. It allows class instances to be reused and saves important resources. This relieves the burden of ensuring thread safety, but does not eliminate it altogether. You should still check for problems when your code accesses files or the database. Further details on web applications and threads can be found at http://java.sun.com/webservices/docs/1.0/tutorial/doc/Servlets5.html#64386.

Exercise 3

Search the Internet and find out about the Dining Philosophers problem. What is it, and what solutions are there to solve it?

 

1.14 Expandability


Struts is expandable. You have the code and can easily reach the developer of that code over the mailing list. You are free to expand given classes and to increase their functionality. Of course, you will need to plan your steps thoroughly and format your problem exactly. Before posting questions, check the mailing lists to see if the solution is already available. Struts is used worldwide and so the problems and solutions are repeated frequently. Also be aware that Struts is continually changing from version to version, and your modifications may well become obsolete or at least require significant revision.

 

1.15 Debugging Struts Applications


Struts offers no help in debugging applications. Modern IDEs, such as WSAD, offer a range of debugging features. They can set the breakpoints at the point where the execution is suspended and you can examine the contents of variables or step through the application line by line.

Most of the time, though, log entries are used for debugging. These are discussed in detail in Chapter 5.

 

1.16 Some Experiences


Here we discuss the pros and cons of Struts for real-life development. The following summarizes a few personal experiences and also includes the views expressed by a couple of developers with different fields of expertise.

1.16.1 Struts in Universities and Colleges

Some readers might be learning Struts as part of university or college tuition. If you are in such a situation, try to convince your instructor to set you a challenging application to develop in conjunction with several other developers working as a team. Or even better, one group writes the application and then the other group has to expand it and maintain it. Such an approach is perhaps the only way to get a grip on the techniques and the problems. A struts-config.xml with ten statements is easier to maintain than one with 100 or 1000 statements. Short mapping names help shrink the file length, but in a complex project, long names tend to be more useful.

1.16.2 Struts in the Enterprise

If you ask developers about their experiences with Struts, you will hear one theme resurface many times: support for forms and multilingualism.

Every now and then, you will come across a developer who believes that JSTL or Java Server Faces is a better alternative. Experience has shown that one needs to be wary of such arguments as they are often based on some article or tutorial and not practical project experience.

1.16.3 Struts from a Tester’s Point of View

In larger projects, there is usually a separate test team. The developers remain responsible for conducting their own tests on the code (usually with JUnit) and the testers test the user transactions. The testers look at the application as a black box and the best ones have a sense for errors that a developer would never think of.

The principle of conducting unit tests on business logic is widely accepted and put into practice, but there is a view that user interface components cannot be tested at all or can be tested only at substantial expenditure.

There are many possibilities for testing websites:

As for Struts, two things to watch out for are:

  • Forms are often filled in over several sequential steps (such as entry, confirmation, error correction). It’s not enough to use HTML parameters to hold the data entered in the form fields, and session objects must be used. Tests for such forms can rapidly become very costly, and small changes in struts-config.xml can have enormous effects.

  • Multi-language files tend to diverge quickly. Some entries may be missed out or just copied from the default language, or worse, incorrectly translated. This is very hard to test. Only errors where an entry exists can be traced by calling all pages. A small crawler, written with HTTPUnit, can check all links for validity and also find certain words in the accessed sites such as ‘error’, ‘exception’, and so on.

1.16.4 Struts in Project

Responses of two developers from Switzerland who worked on an extensive project (following the Rational Unified Process model, with occasionally over 40 project participants) about the advantages and disadvantages of Struts are put together here.

Developer 1: Björn

Advantages
  • Struts requires little training time, thanks to the clear and logical separation into "pure" JSPs, Actions, Forms, and XML configuration files.

  • The Tiles framework bundled with Struts (but disabled by default) offers a pleasant alternative to frames. A strong design allows good reusability of Actions, Tiles, and concurrent JSPs.

  • 99.9% scriplet-free JSP pages.

  • Good Taglibs (for example, logic).

Disadvantages
  • Names of attributes in struts-config.xml are often not intuitive.

  • Debugging is especially difficult, because of unclear error messages, such as Form bean not found, and frequent failure to log exceptions. This is particularly bothersome with trivial errors like typing incorrectly cased letters in form names.

  • The Validation Framework (validation.xml) is mostly unusable and also harder to execute than individual validation in the Form class.

Conclusion
  • Struts will be here for a long time.

Developer 2: Thorsten

Advantages
  • Clarity—the flow of the pages (although there are exceptions).

  • Internationalization and debugging.

  • Code can be removed from JSPs due to the extensive Taglibs.

  • As widely popular open-source software, there is good support through mailing lists and forums.

Disadvantages
  • Constantly changing naming convention, which is often inconsistent.

  • Tiles and Validator do not have good tool support, although there is work going on in this area. For example, the Struts Console (http:// www.jamesholmes.com/struts/console/), briefly mentioned in Chapter 13, offers some helpful features.

Conclusion
  • No application should be made without Struts!

 

Summary


Struts is well suited for extensive (from the development point of view) Java-based websites. It is definitely not a finished diamond and it has many rough edges, which can cause confusion. Despite very good experience with its usage form validation and many other invaluable features, there are a couple of words of warning I’d like to give before we get stuck into the rest of the book.

Internationalization with Struts is very straightforward, but that alone does not justify adopting Struts because it could be readily implemented by other means. The official documentation is woefully inadequate, but this is compensated for by the wide range of books and excellent mailing lists.

The interchangeable design offered by Tiles can be seen as an unnecessary complication. Here are a couple of reasons:

  • The basic intermix of the design is nothing but the movement of frames. Pictures, fonts, and colors make a site much more complicated, but not necessarily any more compelling.

  • The success of sites like EBay and Amazon lies in the fact that these sites have a simple no-frills design and that the modifications are phased in gradually.

Whether or not you agree with these views on Tiles, by the end of this book, you’ll hopefully agree on the overall effectiveness and value of Struts. In time, we will see to what extent Java Server Faces and the JSTL can live in harmony with Struts, or whether, as some predict, Struts will come to replace them.

About the Author

  • Stephan Wiesner

    Stephan Wiesner was born in October 1973 in Lüneburg, Germany. He graduated in business informatics in 2003. He got introduced to Struts during his studies. He didn’t understand the official documentation for Struts and therefore started to develop his own documentation. Feedback from all over the world encouraged him and finally he published it as a book. He currently lives and works in Lucerne, Switzerland, as a QS consultant and test manager.

    Browse publications by this author
Learning Jakarta Struts 1.2: a concise and practical tutorial
Unlock this book and the full library for FREE
Start free trial