1、Best practices for Struts development Palaniyappan Thiagarajan, Pagadala Suresh Struts: A brief introduction Struts, an open source framework you can use to build Web applications, is based on the popular Model-View-Controller (MVC2) design paradigm. The framework is built upon standard technologies
2、 like Java Servlets, JavaBeans, ResourceBundles, and XML, and it provides flexible and extensible components. Struts implements the Controller layer in the form of ActionServlet and recommends building the View layer using JSP tag libraries. Struts also provides a wrapper around the Model layer thro
3、ughAction classes. Figure 1 illustrates the Struts framework based on the Model-View-Controller design. Figure 1. Struts and MVC Overview of Struts components First, well explain the Struts components in the context of best practices and the role each one plays in your Web application development. A
4、ction Every Action of your application extends Struts org.apache.struts.action.Action. These Action classes provide an interface to the applications Model layer, acting as a wrapper around the business logic. Each Action class must provide its case-specific implementation to the perform() method. Th
5、e perform() method always returns a value of type ActionForward. ActionForm Every ActionForm of your application extends Struts org.apache.struts.action.ActionForm. ActionForms are simple JavaBeans that encapsulate and validate request parameters. To validate your request data, your ActionForms vali
6、date() method must give a case-specific implementation. ActionForms serve as a carrier of request data to the Action class. A JSP object combines with a respective ActionForm to form your applications View layer, where almost every form field of the JSP object maps to an attribute of the correspondi
7、ng ActionForm. JSP custom tag libraries The JSP custom tag libraries are a collection of actions presented as tags. This is a powerful feature of the JSP Specification 1.1; it allows you to separate presentation from other application tiers. The libraries are easy to use and you can read them in XML
8、-like fashion. You can easily maintain the JSP components by minimizing the use of Java scriptlets in them. The JSP tags that Struts provides include HTML, logic, and bean tags. ActionErrors You use ActionErrors to support exception handling. An ActionError traps and propagates an application except
9、ion to the View layer. Each one is a collection of ActionError instances. ActionErrors encapsulate error messages, while the in the Presentation layer renders all error messages in the ActionError collection. Best Practice 1. Reuse data across multiple ActionForms Now that you are familiar with the
10、Struts components, we will continue by showing you ways to get the most out of the framework. First, Struts recommends that you associate every JSP object with an ActionForm, which encapsulates data represented in the screen. You access the form data in the JSP object using accessory methods found i
11、n ActionForm. Listing 1 shows the conventional use of ActionForm tag in the View layer. Listing 1. Using ActionForm in JSP The ActionForm called BP1AForm includes the attribute attrib1, as well as its getter and setter methods. In the configuration filestruts-config.xml, the action /bp1 maps to bp1A
12、Form using the name attribute. This facilitates data display in the JSP. To implement this best practice, Struts recommends you do two things: 1. Create a JavaBean (BP1BForm) with attributes that form an attribute subset in BP1AForm, along with the attributes getter and setter methods. 2. Replace th
13、e attributes in BP1AForm with the bean BP1BForm by associating the bean with BP1AForm. Now you can access this attribute subset in BP1AForm through BP1BForm. Listing 2 shows you how. Listing 2. Accessing form attributes in JSP Best Practice 2. Use Action class to handle requests Typically when using
14、 the Struts framework, for every action the JSP component requests your application to execute, the application must extend Struts org.apache.struts.action.Action to create an Action class. This individual Action class interfaces with the applications Model layer while processing the request. To imp
15、lement this practice, Struts recommends you follow these steps: 1. Create an Action class, say BP2Action, by extending org.apache.struts.action.Action. 2. Create all other Action classes in your Web application by extending BP2Action. 3. In BP2Action, create a method performTask(), as in public abst
16、ract ActionForward performTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException. 4. In BP2Action add one or more generic methods to the application, for example serverSideValidate(). You can decide on the methods a
17、ccess modifier by considering the following factors: o If all Action classes must implement this method, make it abstract. o If some Action classes will provide a case-specific implementation, declare the method protected and give it a default implementation. 5. In BP2Action, declare method perform(
18、) as final. Invoke the above generic method, which must always be called before processing the request. Now call the method performTask() created in step 3. 6. In every Action class extending BP2Action, add method performTask() with a case-specific implementation. Advantages This practice has two ma
19、in advantages. First, it helps you avoid redundant code in every Action class of your Web application. Second, it gives the application more control over generic tasks by centralizing the behavior in one Action class. Best Practice 3. Use ActionForm to work on session data In a Struts-based Web appl
20、ication, each ActionForm extends org.apache.struts.action.ActionForm. These ActionForms encapsulate page data and provide a validation framework to validate request parameters. Most Web applications maintain data in session to make them available throughout the application. This best practice addres
21、ses this Web application feature. It allows methods toSession() and fromSession() to move session data to and from the form data. Thus, it addresses session data maintenance in a Web application. To adhere to this practice, follow these steps: 1. Create an abstract class named BP3Form by extending o
22、rg.apache.struts.action.ActionForm. 2. In BP3Form, add methods with access modifiers as in public abstract void toSession(SessionData sessionData) and void fromSession(SessionData sessionData). 3. In every ActionForm, extend BP3Form and implement the abstract methods in which the form data is transp
23、orted to and from the session. 4. The corresponding Action class may determine the order in which these methods are called. For example, you could invoke method toSession() on the ActionForm just before actionForward is determined. When to use this practice This practice is most useful when session
24、data is maintained as a single object and/or every page manipulates or uses session data. Best Practice 4. Handle exceptions effectively Conventionally, when an application exception occurs in an Action class, the exception is first logged. Then the class creates anActionError and stores it in the a
25、ppropriate scope. This Action class then forwards control to the appropriate ActionForward. Listing 3 shows how Action class handles exceptions. Listing 3. Exception handling in an Action class try /Code in Action class catch (ApplicationException e) /log exception ActionErrors actionErrors = new Ac
26、tionErrors(); ActionError actionError = new ActionError(e.getErrorCode(); actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError); saveErrors(request, actionErrors); While conventional exception handling procedures save exception information in every Action class, best practice 4 aims to avoid redundant code while handling exceptions. To use this practice, Struts recommends following these steps: