Struts as a Presentation Framework


Struts as a Presentation Framework

This section discusses some of the most common requirements that are essential for a viable presentation framework. Along with identifying the requirements, we map these to the features offered by Struts and corresponding usage scenarios.

MVC Implementation

The MVC (Model-View-Controller) architecture is a way of decomposing an application into three parts: the model, the view, and the controller. It was originally applied in the graphical user interaction model of input, processing, and output.

click to expand

Model A model represents an application's data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The services that a model exposes must be generic enough to support a variety of clients. By glancing at the model's public method list, it should be easy to understand how to control the model's behavior. A model groups related data and operations for providing a specific service; these groups of operations wrap and abstract the functionality of the business process being modeled. A model's interface exposes methods for accessing and updating the state of the model and for executing complex processes encapsulated inside the model. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.

View The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients. The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.

Controller The controller is responsible for intercepting and translating user actions into command objects [Gof] that invoke methods on the model's public API. The controller is responsible for selecting the next view based on user actions and the outcome of model operations.

In a J2EE-based application, MVC architecture is used for separating business layer functionality represented by JavaBeans or EJBs (the model) from the presentation layer functionality represented by JSPs (the view) using an intermediate servlet-based controller. However, a controller design must accommodate input from various types of clients, including HTTP requests from web clients, WML from wireless clients, and XML-based documents from suppliers and business partners. For the HTTP Request/Response paradigm, incoming HTTP requests are routed to a central controller, which in turn interprets and delegates the request to the appropriate request handlers. This is also referred to as MVC Type-II (Model 2) Architecture. Request handlers are hooks into the framework provided to the developers for implementing request-specific logic that interacts with the model. Depending on the outcome of this interaction, the controller can determine the next view for generating the correct response.

Note 

In this book, the term Request Handler is used interchangeably with Action class and its subclasses.

The following is an illustration of the MVC implementation in Struts. Struts implements the MVC pattern using the Service to Worker pattern [Core]; we discuss this further in the section "Struts MVC Semantics."

click to expand

The following discusses the interactions depicted in the preceding illustration.

Controller

In Struts, the Controller is implemented by the ActionServlet class. The ActionServlet is declared in web.xml (the deployment descriptor) as follows:

<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>
 

All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows:

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

A request URI that matches this pattern will have the following form: http://www.my_site_name.com/mycontext/action_Name.do.

The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /*, as shown here:

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

A request URI that matches this pattern will have the following form: http://www.my_site_name.com/mycontext/do/action_Name.

In Struts 1.1, the Struts required configurations are loaded in the ActionServlet.init() method. The configurations control the behavior of the framework; this includes mapping of URIs to request handlers (discussed in section "Model Interaction with Request Handlers"), configuring message resources, providing access to external resources via plug-ins, and so on. In fact, processing of incoming requests actually occur in the RequestProcessor to which ActionServlet delegates all the input requests.

Dispatcher

All incoming requests are delegated by the controller to the dispatcher, which is the org.apache.struts.action.RequestProcessor object.

Note 

The behavior of the dispatcher, and the behavior of the request handlers that the dispatcher interacts with, is controlled via a configuration file struts–config.xml. Various aspects of this configuration file are explained throughout this chapter.

The RequestProcessor examines the request URI for an action identifier, creates a request handler instance using the information in the ActionMapping configuration object (explained in the next section), and calls the requesthandler.execute method. The execute method of the request handler is responsible for interacting with the application model. Depending on the outcome, the request handler will return an ActionForward configuration object (ActionForward is the runtime representation of the <forward> element and is explained in the section "Navigation Using ActionForward") to the RequestProcessor. The RequestProcessor will use the ActionForward object for invoking the next view by calling either RequestDispatcher.forward or response .sendRedirect, depending on the configuration.

Command Pattern Using ActionMapping

Struts provides a declarative way to specify the mapping between the servlet path in the request URI and an appropriate request handler using XML syntax. This implementation is very similar to the command pattern [Gof]. The following snippet is from the struts-config.xml file; these declarations are used for creating an ActionMapping configuration object, which is the runtime representation of the <action> element.

<action-mappings>
    <action path="/PortalAllianceRegistration"
            type="com.gc.prez.admin.PortalAllianceRegistrationAction"
            name="PortalAllianceRegistrationForm"
            scope="session" validate="false">
        <forward name="ShowPage" path="/2_1_PortalAllianceRegistration.jsp"/>
        <forward name="EnterPortalID" path="/2_3A_EnterPortalID.jsp"/>
        <forward name="success" path="/2_SiteAdministratorServicesMainPage.jsp"/>
    </action>
</action-mappings>
 

Note 

All examples used in this chapter are from Chapter 5. Should you need to explore the examples in parallel (not necessary), please refer to the accompanying source distribution for fully functional code.

The following briefly explains the attributes used in the preceding declaration:

path The context relative path in the HTTP request that is used for identifying this action mapping.

type Class name that will be used for creating an instance of the request handler for handling this request.

name The logical name of a JavaBean, also called a form-bean, that will be used to hold form data. The form-bean will be saved in the specified scope using this name.

scope Request or session scope for saving the form-bean.

start sidebar
Dynamic URL Generation

Dynamic URL generation for the action attribute using the custom org.apache.struts .taglib.html.FormTag (explained further in Chapter 5) will protect the HTML documents from being adversely impacted as a result of change of context path or <url-pattern>. For a *.do URL pattern, the custom FormTag <html:form action="/ editCustomerProfile?customerType=preferred"> will dynamically generate an HTML <form> tag with the action attribute containing the following server-relative URL:

<form action="/contextPath/editCustomerProfile.do?customerType=preferred"/>
 

end sidebar

The path attribute shown in the preceding snippet maps to the action attribute of the HTML <form> element. The declarative specifications prevent hard coding of mappings in the code base and enable convenient visualization of how servlet path specifications in HTML forms are mapped to instances of request handlers; in addition, application behavior and navigation semantics can be changed by simply altering the action mappings. A request handler is a subclass of the Struts-provided Action class.

Using the name attribute, an action mapping can declaratively specify a JavaBean whose properties will hold the parameters from the HTTP request; this JavaBean is subclassed from the ActionForm class. The name in the action mapping declaration is a unique identifier using which the instances of ActionForm classes are stored in the specified scope. The ActionForm subclass is declared in the struts-config.xml file using the <form-beans> tag as follows.

<form-bean name="PortalAllianceRegistrationForm "
       type="packageName.PortalAllianceRegistrationForm "/>
 

Model Interaction with Request Handlers

A subclass of Action is used as an adaptor between incoming requests and the model. The Action subclass, also called the request handler, is created specific to every request. The base Action class provides common functions for accessing framework-related resources and methods for saving errors detected by the execute() method of its subclass. The errors are subsequently extracted and displayed in the HTML form using the custom org.apache.struts.taglib.html.ErrorsTag as explained in the section "Displaying Errors with ErrorsTag." The execute() method of a request handler should contain control flow for dealing with request parameters and the associated ActionForm, it should encapsulate model interaction semantics, and it should provide the next view based on the outcome of model operations. Request handlers are cached by the RequestProcessor when first created, and subsequently made available to other incoming requests; as such, request handlers must not contain user-specific state information; also, request handlers must synchronize access to resources that require serialized access. More discussion on request handlers is available in the section "Request Handler Semantics."

The following is a simple request handler PortalAllianceRegistrationAction. Refer to the GreaterCause directory in the accompanying source distribution for complete code listing.

public class PortalAllianceRegistrationAction extends Action {
    public ActionForward execute( ActionMapping mapping, ActionForm form,
    HttpServletRequest req, HttpServletResponse res ) throws Exception {
        PortalAllianceRegistrationForm regForm =
                             ( PortalAllianceRegistrationForm )form;
        String action = regForm.getAction();
        if ( action.equals( "Create" ) )
        { return ( createRegistration( mapping, form, req, res ) ); }
        else if ( action.equals( "Update" ) ) {
            return ( updateRegistration( mapping, form, req, res ) );
        }
        else if ( action.equals( "View" ) )
        { return ( viewRegistration( mapping, form, req, res ) ); }
        else { return null; }
   }
   public ActionForward createRegistration( ActionMapping mapping,
   ActionForm form, HttpServletRequest req,
   HttpServletResponse res ) throws Exception {
   ..
   ..
   //return an ActionForward object for displaying the next view
   }
   public ActionForward updateRegistration( ActionMapping mapping,
   ActionForm form,
   HttpServletRequest req, HttpServletResponse res ) throws Exception {
   ..
   ..
   //return an ActionForward object for displaying the next view
   }
   public ActionForward viewRegistration( ActionMapping mapping,
   ActionForm form,
   HttpServletRequest req, HttpServletResponse res ) throws Exception {
   ..
   ..
   //return an ActionForward object for displaying the next view
   }
}
 

Navigation Using ActionForward

ActionForward objects are configuration objects. These configuration objects have a unique identifier to enable their lookup based on meaningful names like "success," "failure," and so on. ActionForward objects encapsulate the forwarding URL path and are used by request handlers for identifying the target view. ActionForward objects are created from the <forward> elements in struts-config.xml. The following is an example of a <forward> element in Struts that is in the local scope of an <action> element:


<action-mappings>
   <action path="/PortalAllianceRegistration"
           type="com.gc.prez.admin.PortalAllianceRegistrationAction"
           name="PortalAllianceRegistrationForm"
           scope="session" validate="false">
      <forward name="ShowPage" path="/2_1_PortalAllianceRegistration.jsp"/>
      <forward name="EnterPortalID" path="/2_3A_EnterPortalID.jsp"/>
      <forward name="success"
               path="/2_SiteAdministratorServicesMainPage.jsp"/>
   </action>
</action-mappings>
 

Global <forward> elements are typically specified for common destinations within the application as illustrated by the following example:

<global-forwards>
   <forward name="success" path="/1_HomePage.jsp"/>
   <forward name="failure"
         path="/1_3_AdministratorLoginFailure.jsp"/>
</global-forwards>
 

Based on the outcome of processing in the request handler's execute method, the next view can be selected by a developer in the execute method by using the convenience org.apache.struts.action.ActionMapping.findForward method while passing a value that matches the value specified in the name attribute of the <forward> element. This is illustrated by the following snippet.

return mapping.findForward( "ShowPage" );
 

The ActionMapping.findForward method will provide an ActionForward object either from its local scope, or from the global scope, and the ActionForward object is returned to the RequestProcessor for invoking the next view using the RequestDispatcher.forward() method or response.sendRedirect. The RequestDispatcher.forward method is called when the <forward> element has an attribute of redirect="false" or the redirect attribute is absent; redirect="true" will invoke the sendRedirect method. The following snippet illustrates the redirect attribute usage:

<forward name="success" path="/1_HomePage.jsp" redirect="true"/>
 

The <controller> element in the struts-config.xml file provides yet another feature for controlling how the <forward> element's name attribute is interpreted; the <controller> element is used in conjunction with the input attribute on the <action> element, as shown here:

<action-mappings>
   <action path="/PortalAllianceRegistration"
           type="com.gc.prez.admin.PortalAllianceRegistrationAction"
           name="PortalAllianceRegistrationForm"
           scope="session"
           input="ShowPage"
           validate="false">
      <forward name="ShowPage" path="/2_1_PortalAllianceRegistration.jsp"/>
      <forward name="EnterPortalID" path="/2_3A_EnterPortalID.jsp"/>
      <forward name="success"
               path="/2_SiteAdministratorServicesMainPage.jsp"/>
   </action>
</action-mappings>

<controller>
   <set-property property="inputForward" value="true"/>
</controller>
 

The preceding <action> element has an input attribute with a forward name; this forward name is identical to the one used in the <forward> element. With the preceding <controller> configuration, when the ActionForm.validate returns a non-empty or non-null ActionErrors object, the RequestProcessor will select the <forward> element whose name attribute has the same value as the input attribute of the <action> element; unless overridden by a subclass of RequestProcessor, this behavior is standard when validation errors are encountered. With the following <controller> element declaration, when the ActionForm.validate returns a non-empty or non-null ActionErrors object, the input attribute provides a forwarding URL instead of an ActionForward name to which the forward occurs. In the absence of the inputForward property, this is the default behavior.

<controller>
     <set-property property="inputForward" value="false"/>
</controller>
 

The forward is done to the specified path, with a / (slash) prepended if not already included in the path specification. For forward or redirect, URLs in Struts are created internally by the RequestProcessor with the following structure:

  • If redirect=true, the URL is created as /contextPath/path because for HttpServletResponse.sendRedirect the container interprets a URL with a leading / (slash) as relative to the servlet container root.

  • If redirect=false, the URI is created as /path because ServletContext.getRequestDisptacher uses context-relative URL.

Internationalization and Localization Support

Internationalization, or I18N, is the process of engineering an application such that it can be adapted to various languages and regions without requiring any change to the application logic. For internationalization support, an application must consider the following:

  • Textual content, error messages, exception messages, and labels on GUI components must be externalized into resource files. These resource files will contain locale-specific information as discussed shortly.

  • Date, time, currency, numbers, measurements, and phone numbers must be formatted based on local preferences and culture.

In today's global marketplace, it is important to design the applications with internationalization; doing this upfront takes relatively less time and effort than incorporating I18N after the application has been developed. The JDK provides the Locale class that is used by internationalized classes to behave in a locale-sensitive way. A Locale object represents a specific geographical, political, or cultural region. The following is a discussion on how Struts implements I18N and localization.

The Locale Object

Struts classes providing I18N support retrieve the locale-specific information from the HttpSession using getAttribute(Action.LOCALE_KEY). The Locale object is saved in the session in several different ways, as explained next.

Using HtmlTag The custom tag org.apache.struts.taglib.html.HtmlTag is inserted in a JSP as <html:html locale="true">. This is a declarative way of populating Locale in the session. When locale=true is specified, the tag logic will retrieve the Locale object using the HttpServletRequest.getLocale() method. The getLocale() method returns the preferred Locale that a client browser will accept content based on the Accept-Language header. A default locale for the server is returned when the client does not provide an Accept-Language header. A session object is created if it does not exist, and the Locale object is then stored in the session object using Action.LOCALE_KEY. The HTML tag is subsequently written to the output stream with the lang attribute set to the language specified in the locale. The Locale object is stored only once in this manner; subsequent locale=true specification will not be able to replace the Locale object in the session. This method of setting locale works best when the users have their browsers set with the preferred locale list.

Using the Action Object For programmatically changing the Locale object, the Action class provides the setLocale() method for saving the Locale object in the session using Action.LOCALE_KEY. This method of setting locale works best when a user has the option of choosing locale in the HTML form by clicking a UI component. However, using this method can sometimes cause problems if locale-specific resources are preloaded and a user is allowed to switch locale in the middle of a process flow. It is best to allow this functionality in a controlled manner and reset all locale-specific resources when a locale change is requested.

Using <controller> Element Under this scheme, the <controller> tag from the struts-config.xml file is used to flag the RequestProcessor to get the locale from the HttpServletRequest object and put it in the session using Action.LOCALE_KEY. This is illustrated here:

<controller>
     <set-property property="locale" value="true"/>
</controller>
 

If value=true, then the Locale object obtained from request getLocale() is saved in the session if not previously saved.

Internationalized Messaging and Labeling

For I18N support, all error messages, instructional messages, informational messages, titles, labels for GUI components, and labels for input fields must be stored externally and accessed in a locale-specific way. The Struts framework provides the MessageResources class that mimics the ResourceBundle class provided by the JDK. Locale-specific resource bundles provide a way of isolating locale-specific information. Resource bundles belong to families whose members share a common base name, but whose names also have additional components that identify their locales. The default resource bundle has the same name as the base name of a family of resource bundles and is the bundle of last resort when locale-specific bundles are not found. Locale-specific bundles extend the base bundle name with locale-specific identifiers like the language, country, and variant of a locale. Consider the following example.

If base ResourceBundle name is MyApplicationResources, resource bundles belonging to this family may be identified as follows:

  • MyApplicationResources_en identifies the bundle for the English language.

  • MyApplicationResources_fr identifies the bundle for the French language.

  • MyApplicationResources_fr_FR identifies the bundle for the French language for France.

  • MyApplicationResources_fr_CA identifies the bundle for the French language for Canada.

If the desired locale is fr_FR and the default locale is en_US, the search order for accessing resource bundles can be summarized as follows. The search goes from being more specific to less specific:

  • MyApplicationResources_fr_FR The desired resource bundle

  • MyApplicationResources_fr Less specific bundle if the desired bundle is not found

  • MyApplicationResources_en_US The default bundle if no matching bundles are found thus far

  • MyApplicationResources_en Less specific bundle if the default bundle is not found

  • MyApplicationResources The base bundle

Struts provides a facility for accomplishing the preceding mechanism using MessageResources objects. MessageResources objects are initialized from the key/value pairs specified in underlying properties files. You have to specify only the base name for a MessageResources properties file in the struts-config.xml file to access all the locale-specific properties files using search order that is similar to the one specified for the ResourceBundle(s). The following depicts how message resources are declared in the struts-config.xml file:

<message-resources parameter="packageName.MyApplicationResources" key="MyResources"/>
 

The value of the parameter attribute declares the base non-locale-specific properties file. This base resource file will have the name MyApplicationResources.properties, while locale-specific files will have the name MyApplicationResoures_localeSpecificExtension.properties. For each application, we can specify one or more base bundle names. MessageResources objects are created by the controller, that is ActionServlet, and saved in the ServletContext using either a generic key Globals.MESSAGES_KEY (same as Action.MESSAGES_KEY) or using the key attribute provided in the <message-resources> element (in case of multiple MessageResources).

For accessing message resources objects in request handlers, the Action class provides a convenience method—Action.getResources—for retrieving a message resource from the ServletContext using the key (i.e., unique identifier) associated with the MessageResources object. Each MessageResources object will be responsible for getting locale-specific messages by accessing the underlying set of locale-specific properties files; the properties files are identified by the base MessageResources name specified by the parameter attribute in the <message-resources> tag.

To retrieve a locale-specific message, use MessageResources.getMessage while passing locale and message key as arguments as follows:

protected static MessageResources messages =
   MessageResources.getMessageResources("packageName.MyApplicationResources ");
 

The locale can be retrieved from the session using Action.LOCALE_KEY. When an Object[] is provided as an argument for MessageResources.getMessage, the message retrieved is treated as a message format pattern and is converted to a MessageFormat object. The MessageFormat object is subsequently used for calling the MessageFormat.format method while passing the object[] to be appropriately formatted and inserted into the pattern at appropriate places. The MessageFormat class is not locale specific, therefore the corresponding message format pattern and the Object[] must take localization into account. MessageResources API provides several convenience methods for retrieving messages; the corresponding Javadoc is available at http://jakarta.apache.org/struts/api/index.html. On most occasions, the logic for retrieving messages from a resource bundle is transparent to the Struts user; this is explained in the next section. Refer to the section "Message Resources Semantics" in this chapter for additional information on this topic.

Error Handling

Most form interactions require that the user be informed of the possible outcome of the form submission. Displaying error and informational messages in a consistent manner is a desirable feature of a framework. In the preceding section, we discussed locale-specific messaging using the MessageResources objects. The set of properties files associated with each MessageResources object has key/value pairs. A Struts-based application will accumulate, for message lookup, the keys associated with validation and informational messages in an ActionErrors object as a precursor to accessing resource bundles. The following static model illustrates the classes involved in the error handling mechanism provided by Struts.

click to expand

We will briefly discuss the interactions depicted in the preceding illustration. This discussion will provide us with insight on how message keys are captured in Struts to get locale-specific messages, and how the messages are rendered in a consistent manner in the view. For this discussion the view component is a JSP.

Identifying Errors with ActionError

Implementations of Action.execute or ActionForm.validate form. validation (discussed in the section "Storing Form Data Using ActionForm") should capture validation and application-specific errors in ActionErrors objects, which aggregates ActionError objects. An ActionError object consists of a message key and optionally an object[] to be used for parametric replacement in the retrieved message. Refer to earlier section "Internationalized Messaging and Labeling" for relevant information. ActionError objects must be created without worrying about the locale or the associated resource bundles. We will deal with I18N when the ActionError objects are used for retrieving messages. Refer to the ActionError API for a complete list of available convenience methods for creating ActionError objects. Once an ActionError object is created, it should be added to the ActionErrors object using the ActionErrors.add method while passing as arguments the ActionError and the property name for which a validation error was detected. The following snippet from the ManagePortalAllianceAction class illustrates this. Chapter 5 discusses the implementation of the sample application in detail.

public ActionForward execute( ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse res ) throws Exception {
   ManagePortalAllianceForm portalForm =
                 ( ManagePortalAllianceForm )form;
   ActionErrors errors = portalForm.validate( mapping, req );
   String action = portalForm.getAction();
   if ( !errors.empty() && portalForm.getPage() == 1 ) {
      saveErrors( req, errors );
      return mapping.findForward( "EnterPortalID" );
   }
   if ( ( !errors.empty() ) && ( portalForm.getPage() == 2 ) &&
   ( action.equals( "updateProfile" ) ) ) {
     saveErrors( req, errors );
   return mapping.findForward( "ShowPortalProfile" );
   }
   if ( ( !errors.empty() ) && ( portalForm.getPage() == 2 ) &&
   ( action.equals( "navigationBarSetup" ) ) ) {
     saveErrors( req, errors );
     return mapping.findForward( "ShowNavigationBarSetup" );
   }
// rest of the code
}
 

Within the associated ManagePortalAllianceForm, the validate() method will add error messages to the errors object as follows:

public ActionErrors validate( ActionMapping mapping,
       HttpServletRequest req ) {
       ActionErrors errors = new ActionErrors();
      if ( ( page ==1)&&(( portalID == null ) ||
         ( portalID.trim().length()<1))){
         errors.add( "portalID", new ActionError( "error.portalID.required" ) );
      }
      else if ( ( page ==2)&&( action.equals( "updateProfile"))){
         errors = super.validate( mapping, req );
         if ( searchLimit.intValue() < 10 ) {
          errors.add( "searchLimit",
              new ActionError( "error.PortalAllianceProfile.SearchLimit" ) );
         }
      }
 

For saving error messages not related with a property, a convenience instance member ActionErrors.GLOBAL_ERROR is available for use in place of a property argument in ActionErrors.add(). Usage of property name in creating an ActionErrors object is clarified in the upcoming section "Compiling Errors ActionErrors."

Compiling Errors with ActionErrors

ActionErrors objects hold all ActionError objects in a HashMap whose key is the name of the property for which messages have been accumulated, and the value is an ActionMessageItem object. ActionMessageItem is declared as an inner class of ActionMessages. Each ActionMessageItem object consists of a unique sequence number and an ArrayList object representing all possible validation errors for a given property. The sequence number is used for sorting the ActionMessageItem collection such that validation errors are reported according to the property that was first flagged as invalid. ActionErrors.get returns an Iterator on an ArrayList containing ActionError objects. This Iterator object is referenced by the custom tag ErrorsTag and will be discussed in the next section, "Displaying Errors with ErrorsTag."

In request handlers, i.e., in the Action.execute method, ActionErrors should be saved in the HttpServletRequest using the attribute name Action.ERROR_KEY; this is done by calling a convenience saveErrors method on the base Action class while passing as arguments the request object and the ActionErrors object The ActionErrors generated as a result of ActionForm.validate are saved by RequestProcessor (the dispatcher) in the request object using Action.ERROR_KEY. The next view can use the ErrorsTag for retrieving the ActionErrors object; the ErrorsTag can be used in a JSP as follows:

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:errors/>
 

The ActionErrors class extends the ActionMessages class. ActionErrors provides the static member GLOBAL_ERROR and ActionMessages provides the static member GLOBAL_MESSAGE; these static members can be used as keys when the messages are not property specific. For saving the ActionMessages object in a request handler, the convenience Action.saveMessages method can be used while passing the request object and the ActionMessages object; the ActionMessages object is saved in the request using the Action.MESSAGE_KEY.

For simply capturing message keys, without the property name and the substitution parameters, a convenience method org.apache.struts.util.RequestUtils.getActionErrors is available for converting a String object, a String array, or an ErrorMessages object (a Vector of message keys) into an ActionErrors object. For these implementations, the getActionErrors method will use the ActionErrors.GLOBAL_ERROR in place of a property argument.

Displaying Errors with ErrorsTag

This custom tag renders the messages in an HTML document. It retrieves the ActionErrors from the HttpServletRequest using Action.ERROR_KEY and then using the ActionErrors.get() method retrieves an Iterator on an ArrayList containing ActionError objects. For each ActionError object in the ArrayList, a locale-specific message is retrieved and sent to the response stream. By default, the locale object in the session is used; but an alternate locale attribute can be specified for the tag. By default, the resource bundle saved in the ServletContext with the key Action.MESSAGES_KEY will be used unless overridden by the bundle attribute on the tag. You will need to override the resource bundle if more than one base resource file is being used for manageability. As of Struts 1.1 beta 2, an ErrorsTag can only use one resource bundle family (i.e., the bundles have the same base name), therefore all errors in the ActionErrors object must be available in this resource bundle family. Because all ActionError objects within the ActionErrors object are logged by a property name, the messages displayed can be restricted to a single property by specifying a property attribute specification on the ErrorsTag.

The sample application ‘GreaterCause’ uses a default resource bundle ‘ApplicationResources.properties’. Following is a snippet from this properties file.

error.portalID.required=<li>Portal ID must be provided</li>
error.invalidToken=<li>Either this form has been submitted once already, or,
this form is not in proper submission sequence</l1>
error.ein.required=<li>EIN must be provided</li>
 

The ErrorsTag uses message keys ‘errors.header’ and ‘errors.footer’ for providing caption and formatting around error messages, as shown here:

errors.header=<h3><font color="red">Please review following message(s) before
proceeding:</font></h3><ul>
errors.footer=</ul>
 

Exception Handling

In addition to an error handling mechanism, a presentation framework must provide a mechanism for showing locale-specific exceptions of meaning and relevance to the user. A recommended way to do this is to capture the actual exception and its context in a log file and then send a meaningful informational message for assisting the user in determining a suitable course of action. Uncaught exceptions in JSPs are handled by the errorPage mechanism as specified in JSP 1.2 specification. Similarly, uncaught exceptions in servlets are handled using the <error-page> specification in the web.xml deployment descriptor. Struts provides a simple mechanism that is somewhat similar to the error page mechanism provided by JSP and servlet containers. The following configuration can be specified in the struts-config.xml file:

<action path="/editCustomerProfile"
        type="packageName.EditCustomerProfileAction"
        name="customerProfileForm"
        scope="request" input="profile">
   <forward name="profile" path="/CustomerProfile.jsp"/>
   <forward name="success" path="/MainMenu.jsp"/>
   <exception
        key="profile.inaccessible"
        type=" packageName.ProfileAccessException"
        path="/login.jsp"/>
</action>
 

The exception handling mechanism builds on top of the error handling mechanism and therefore uses the MessageResources for providing locale-specific messages. The following static model illustrates the classes involved in the exception handling mechanism provided by Struts. The discussion that follows explains the Exception mechanism provided with Struts.

click to expand

Role of the Dispatcher

As discussed in the section "Dispatcher," the dispatcher (a.k.a. the request processor) calls the execute method of the request handler. Any exception thrown by the request handler is caught by the RequestProcessor and interrogated for a possible match with the <exception> elements in the struts-config.xml file. The RequestProcessor will call the ActionMapping.findException method to find an ExceptionConfig configuration object (ExceptionConfig objects are runtime representations of <exception> elements) whose type attribute matches the type of the exception. If an attempt to find an <exception> configuration for the original exception fails, the findException method will look up the exception superclass chain for a suitable match until it reaches the top of the chain. ActionMapping.findException will search for the <exception> element both in the local scope of the ActionMapping object, and in the global scope.

Global <exception> elements are typically specified for common exceptions within the application as illustrated by the following example:

<global-exceptions>
   <exception
        key="profile.inaccessible"
        type=" packageName.ProfileAccessException"
        path="/logon.jsp"/>
</global-exceptions>
 

If an ExceptionConfig object is found for a given exception type, the RequestProcessor will create an exception handler and call its execute method; this is explained further in the section "Converting an Exception into ActionErrors." The RequestProcessor will forward to the URL specified in the ActionForward object returned by the exception handler.

Exception Handling with AppException

This is a convenience base class for creating exceptions within the request handlers. It encapsulates both, the attribute causing an exception (optional) and associated ActionError object. A subclass of AppException will be responsible for providing the appropriate constructors for correctly instantiating this object by using a message key, and optionally the attribute name and an object[] for parametric substitution. The message key can be extracted from the ExceptionConfig object that corresponds to this exception. Refer to the section "Struts Configuration Semantics" for information on navigating the configuration objects. Refer to the AppException API for an available list of constructors that can be called from the constructor of its subclass. The AppException is passed as an argument in the ExceptionHandler.execute() method.

Converting an Exception into ActionErrors

The RequestProcessor checks the ExceptionConfig for an exception handler specification. The RequestProcessor creates the specified ExceptionHandler and calls its execute() method while passing the AppException as one of the arguments. A default exception handler specification of org.apache.struts.action.ExceptionHandler is preconfigured in the ExceptionConfig object. The ExceptionHandler retrieves the ActionError from the AppException object and creates an ActionErrors object for consumption by ErrorsTag. If the exception is not of type AppException or one of its derived classes, then the ExceptionHandler will create the ActionErrors object using the key specified in the <exception> element; this alleviates the request handler developer from writing extra code for exception handling; however this limits the ability of the framework to call only a single constructor of ActionError that only accepts a key value. Use the handler attribute on the <exception> element to override the default exception handler if desired. The ExceptionHandler or a subclass of ExceptionHandler will create an ActionForward object using the path property of the ExceptionConfig; if this path is not specified, it will use the path specified in the input attribute of the ActionMapping configuration object. The ExceptionHandler will also save the original exception in the request object using Action.EXCEPTION_KEY. A view is free to access this information in any way desired. The Action.EXCEPTION_KEY can be also be used to retrieve and rethrow the original exception for using the error-page mechanism provided by the servlet container.

Once-Only Form Submission

A problem always encountered in developing browser-based clients is the possibility of a form getting submitted more than once. It is apparent that such submissions are undesirable in any eCommerce application. Struts provides a mechanism to protect the model layer from the adverse effect of multiple form submissions by using a token generated by the base Action class generateToken method. To control transactional integrity and atomicity, simply call the saveToken method in a request handler before selecting the next view with an ActionForward.The saveToken method calls the generateToken method to create a unique identifier and then saves it in the session with the key Action.TRANSACTION_ TOKEN_KEY. The FormTag retrieves the token from the session and saves it as a hidden field with the name Constants.TOKEN_KEY.

On a subsequent request, the request handler can check for token validity by calling the convenience isTokenValid method on the base Action class. Should this method return false, the request handler must implement suitable logic to account for the problem. An example of this is illustrated here:

ActionErrors errors = new ActionErrors();
if ( !isTokenValid( req)){
    errors.add( ActionErrors.GLOBAL_ERROR, new ActionError( "error.invalidToken" ) );
    saveErrors( req, errors );
    return mapping.findForward( "ShowPage" );
}
resetToken( req );
 

The isTokenValid() method synchronizes the session object to prevent multiple requests from accessing the token. In the request handlers, the method isTokenValid() must be followed by a resetToken() to remove the token from the session; this will ensure that any subsequent request will result in isTokenValid() returning false, thus preventing a form from multiple submissions. The saveToken() should be called in the request handler to recreate a new transaction token for the next request. A call to the resetToken is not required when the isTokenValid method parameter list includes the reset flag.

Capturing Form Data

The JSP specification provides a standard way for extracting and storing form data at request time in JavaBeans using <jsp:useBean> and <jsp:setProperty>. However, this solution creates a strong coupling between the presentation layer and the JavaBeans; furthermore, the HTML document creator has to be aware of such components and their correct usage in the context of a page. Because the JavaBeans can be created and placed in a specified scope by the <jsp:useBean> tag or by another server component, there could be problems with bean life cycle management between different components sharing the JavaBean. Struts provides a mechanism for extracting, storing, and validating form data; at the same time, it overcomes the shortcomings of the <jsp:useBean> and <jsp:setProperty>.

The following is a recap of the <action> and <form-bean> elements:

<form-bean name="PortalAllianceRegistrationForm"
      type="packageName.PortalAllianceRegistrationForm"/>
<action-mappings>
   <action path="/PortalAllianceRegistration"
           type="com.gc.prez.admin.PortalAllianceRegistrationAction"
           name="PortalAllianceRegistrationForm"
           scope="session" input="ShowPage"
           validate="false">
      <forward name="ShowPage"
               path="/2_1_PortalAllianceRegistration.jsp"/>
      <forward name="EnterPortalID"
               path="/2_3A_EnterPortalID.jsp"/>
      <forward name="success"
               path="/2_SiteAdministratorServicesMainPage.jsp"/>
   </action>
</action-mappings>
 

The preceding snippet maps a JavaBean of type= packageName.PortalAllianceRegistrationForm with name= "PortalAllianceRegistrationForm" (unique identifier) to an <action> element with name= "PortalAllianceRegistrationForm;" the request handler is uniquely identified by the path / PortalAllianceRegistration in the incoming request. The semantics of the form creation and usage are illustrated with the following static model.

click to expand

First, we will explore the semantics of forms processing while employing simple JavaBeans objects. These objects are subclassed from as ActionForm and are also referred to as form-beans. We will then discuss forms processing using the DynaActionForm object that can support dynamic sets of properties at request time.

The following is an abbreviated version of the PortalAllianceRegistrationForm from the sample application. Please note that the ValidatorForm extends the ActionForm. ValidatorForm is discussed in detail in Chapter 5.

public class PortalAllianceRegistrationForm extends ValidatorForm implements
Serializable {
    public PortalAllianceRegistrationForm() {
    }
    public String getPortalID() {
       return portalID;
    }
    public void setPortalID( String portalID ) {
       this.portalID = portalID;
    }
    public String getPortalName() {
       return portalName;
    }
    public void setPortalName( String portalName ) {
       this.portalName = portalName;
    }
    private String portalID;
    private String portalName;
    // rest of the code goes here
    public void reset( ActionMapping mapping, HttpServletRequest req ) {
        portalName = null;
        // rest of the code goes here
    }
    public ActionErrors validate( ActionMapping mapping, HttpServletRequest req ) {
        ActionErrors errors = super.validate( mapping, req ); //Struts Validator
        if ( errors == null ) {
            errors = new ActionErrors();
            // Additional validations to be placed here
        }
        return errors;
    }
}
 

Initializing ActionForm Objects in FormTag

As mentioned earlier in this section, the action URL in the HTML form is mapped to an <action> configuration, which in turn is mapped to a <form-bean> configuration. The URL specified in the action property of the FormTag is translated by the FormTag into a URL whose path structure conforms to the <url-pattern> specified in the deployment descriptor. For extension mapping, this implies that the resource extension is the same as that specified for the <url-pattern>. Therefore, a URL of the form /editCustomerProfile?customerType=preferred, is translated into /contextName/ editCustomerProfile.do?customerType=preferred.

The FormTag calls the org.apache.struts.util.RequestUtils.createActionForm method, which will search for an ActionFormBean configuration object (ActionFormBean is the runtime representation of the <form-bean> element) with a name that matches the name specified on the corresponding <action> element. A new instance of the ActionForm is created using the type attribute of the <form-bean> element; a new instance is created when the ActionForm instance is not found in the specified scope, otherwise the FormTag calls the ActionForm.reset method on the existing form-bean to clear it in preparation for the form data from the next request. The scope is specified by the scope attribute in the <action> element; the new ActionForm instance or the existing reinitialized instance is saved in the specified scope using the name attribute.

Storing Form Data Using ActionForm

The ActionForm-derived objects are used for storing the parameters from a request object, and therefore they are tightly coupled to a user. An ActionForm subclass is a JavaBean with accessor methods for properties corresponding to parameters in the HttpServletRequest object. If an ActionForm object is created by the FormTag (discussed in the preceding section), then in the request subsequent to form rendering by the FormTag, the RequestProcessor (that is, the dispatcher) will access the form from the specified scope; the form to be retrieved is identified by the related action mapping. The RequestProcessor will then reset the form properties, populate the form with request time parameters, and then call the validate method on the form object to perform server-side validation of user input. The validate method is called only when the validate property in the ActionMapping object is set to true; this is the default behavior. The result of validation could be an ActionErrors object, explained in the section "Error Handling," which is used by org.apache.struts.taglib.html.ErrorsTag to display the validation errors to the user. The ActionForm can also be used for storing intermediate model state, which is subsequently referenced by a view (a JSP) for presenting to the user.

An ActionForm class can also be created by the RequestProcessor. This happens when a forward is done to a URL that maps to the controller servlet rather than a JSP and the corresponding action mapping specifies the form property. In this case, an attempt by the RequestProcessor to look up the form-bean may result in the creation of a new ActionForm object if not found in the specified scope. The ActionForm objects are found in the specified scope using the name attribute specified in the <action> element; when a form-bean is found by the RequestProcessor, it is passed to the request handler's execute method. You may also decide to instantiate an action form in a request handler; you may find this need when initializing instance variables based on application state. This is illustrated by the following example.

public class CreateCampaignAction extends Action {

public ActionForward execute( ActionMapping mapping, ActionForm form,
HttpServletRequest req, HttpServletResponse res ) throws Exception {
        ManageCampaignsForm campaignForm = ( ManageCampaignsForm )form;
        // other code appears here
        return ( searchAndSelectNPO( mapping, form, req, res ) );
   }
public ActionForward searchAndSelectNPO( ActionMapping mapping, ActionForm form,
HttpServletRequest req,
    HttpServletResponse res ) {
        ManageCampaignsForm campaignForm = ( ManageCampaignsForm )form;
        SearchAndListNPOForm searchForm =
        ( SearchAndListNPOForm )req.getSession().getAttribute
                   ( "SearchAndListNPOForm" );
        if ( searchForm == null ) {
            searchForm = new SearchAndListNPOForm();
            req.getSession().setAttribute( "SearchAndListNPOForm", searchForm );
        }
        /* Initialize state information with the objective of Search */
        searchForm.setAction( "createNewCampaign" );
        campaignForm.setAction( "createNewCampaign" );
        return mapping.findForward( "ShowSearch" );
   }
}
 

Form objects created for the purpose of providing intermediate model state to the JSP should use request scope; this will ensure that the objects do not hang around after their usefulness expires. By default, all forms are saved in the session scope. The existence of form objects in the session beyond their usefulness could result in wasted memory, as such, the request handlers must track the life cycle of form objects stored in the session. A good practice for capturing form data is to use a single form-bean for related forms that span several user interactions. form-beans can also be used to store intermediate model state, which can be adapted by custom tags for use in a view at response time. Tag usage prevents incorporation of Java code (scriptlets) in the view, thus achieving a good division of responsibility between a web production team that primarily deals with markup, and an application development team that primarily deals with writing Java code. The tags factor out logic for accessing intermediate model state; this logic could be quite complex when accessing nested objects or when iterating through a collection.

Creating ActionForm with Dynamic Properties

A DynaActionForm object is an object with a dynamic set of properties. DynaActionForm extends the ActionForm; its usage permits creation of a form object through declarations made in the struts-config.xml as follows:

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

The RequestProcessor creates, populates, and validates the DynaActionForm in the same way it does ActionForm, i.e., the parameters in the request object are populated in the DynaActionForm for the dynamic set of properties specified in the <form-bean> element; other parameters are simply skipped.

Request Parameter Type-Conversion

This discussion focuses on how String[] type retrieved by Struts framework using request .getParameterValues(parameterName) is converted to the target property type of the form-bean object. The following is a list of supported target types:

java.lang.BigDecimal
java.lang.BigInteger
boolean and java.lang.Boolean
byte and java.lang.Byte
char and java.lang.Character
double and java.lang.Double
float and java.lang.Float
int and java.lang.Integer
long and java.lang.Long
short and java.lang.Short
java.lang.String
java.sql.Date
java.sql.Time
java.sql.Timestamp
 

The target types, i.e., the type associated with form-bean object properties, are found using an introspection mechanism; a Struts-specific custom introspection mechanism is used for DynaActionForm objects. Struts also supports indexed parameter names of the form parameterName[n]; where the index n is zero based. The form-bean methods corresponding to this naming convention are created according to the indexed property design patterns prescribed by the JavaBeans specification, as shown next.

The following methods are used to access all array elements of an indexed property:

public <PropertyType>[] get<PropertyName>();
public void set<PropertyName>(<PropertyType>[] value);
 

The following methods are used to access individual array elements:

public <PropertyType> get<PropertyName>(int index)
public void set<PropertyName>(int index, <PropertyType> value)
 

The following describes the usage scenarios for indexed properties and simple properties:

  1. When the bean property is an array, and the parameter name in the request does not use the indexing notation parameterName[n], the String[] returned by request.getParameterValues(parameterName) is converted to an array of target component type. The ActionForm subclass should be defined with the following method signatures:

    public void set<PropertyName>(<PropertyType>[] value)
    public <PropertyType>[] get<PropertyName>();
    
     
  2. When the bean property is of type array, and the parameter name in the request uses the indexing notation parameterName[n], the String[] returned by request .getParameterValues(parameterName) is assumed to be containing only a single value; as such, only String[0] is converted to the component type of the array. The ActionForm subclass should be defined with the following method signatures that accept an index argument:

    public void set<PropertyName>(int index, <PropertyType> value)
    public <PropertyType> get<PropertyName>(int index)
     

    These method signatures follow the design patterns of indexed properties as stated in the JavaBeans specification. In the absence of these methods, indexed access using the indexing notation is also possible by implementing the following method:

    public <PropertyType>[] get<PropertyName>();
     

    In this scenario, the required array element to set is accessed by the Struts framework by first getting the underlying array object, accessing the element for the given index, and finally setting the accessed object. This pattern can also support a List-based implementation for request parameters that use the indexing notation parameterName[n]. We discuss a List-based implementation next in the section "A Simple Example of Nested Properties."

  3. For simple property types, the String[] returned by request .getParameterValues(parameterName) is assumed to be containing only a single value; as such only String[0] is converted to the target type. For simple properties, the ActionForm subclass should be defined with the following method signatures.

    public void set<PropertyName>(<PropertyType> value)
    public <PropertyType> get<PropertyName>();
     

A Simple Example of Nested Properties

An example of List-based implementation with List update capability is illustrated in this section. Following is a stripped-down version of the JSP code from 2_3_5_1_UpdateCampaigns.jsp that can be found in the GreaterCause directory. In the following snippet, Collection "campaigns" is extracted from the ActionForm "ManageCampaignsForm" using getCampaigns() and saved in the session using the identifier "campaignDTO"; this identifier is subsequently used to retrieve the elements of the collection in the <iterate> tag.

<logic:iterate  name="ManageCampaignsForm" property="campaigns">
   <table>
      <tr>

<%-- Each element of the Collection campaigns (identified in the session by
the identifier campaignDTO) is iterated and the corresponding nested property written
to the output stream. The property indexed="true" will create an index for
each form field where this property is specified; the index is zero based and
increments for each iteration --%>
            <html:hidden name="campaignDTO" property="ein" indexed="true"/>
               <td><bean:write name="campaignDTO" property="ein"/></td>
               <td><bean:message key="prompt.StartDate"/></td>
               <td><html:text name="campaignDTO" property="startDate" size="10"
                   maxlength="10" indexed="true"/></td>
      </tr>
      <tr>
         <td >
         <!-- other HTML appears here -->
         </td>
         <td><bean:message key="prompt.EndDate"/></td>
         <td><html:text name="campaignDTO" property="endDate" size="10"
             maxlength="10" indexed="true"/></td>
      </tr>
   </table>
   <br>
</logic:iterate>
 

The preceding <iterate> tag will result in the following HTML that shows two iterations of the <iterate> logic, and results in indexes [0] and [1]. The field name campaignDTO[0].ein can be decomposed as follows: campaignDTO references the Collection "campaigns" in the ActionForm "ManageCampaignsForm"; the index [0] references the first element of the Collection "campaigns", which is made available using the method getCampaignDTO( int index ) in the ActionForm; the simple property ein is an instance variable of the first element of the Collection "campaigns"; each element of the Collection is an object of the type CampaignDTO. When the form is submitted, the Struts framework applies the updates to the corresponding simple properties in the CampaignDTO by first calling the method getCampaignDTO( int index ); it then applies the form input to the corresponding instance variable in the DTO. It is important to reiterate here that when the framework retrieves the campaign DTO object, the framework takes the responsibility of updating the individual instance variables of campaign DTO objects.

<table>
   <tr>
      <input type="hidden" name="campaignDTO[0].ein"value="EIN0">
      <td>EIN0</td>
      <td>Start Date</td>
      <td><input type="text" name="campaignDTO[0].startDate" maxlength="10"
          size="10" value="2003-12-12"></td>
   </tr>
   <tr>
      <td>
      <!-- other HTML appears here -->
      </td>
      <td>End Date</td>
      <td><input type="text" name="campaignDTO[0].endDate" maxlength="10"
         size="10" value="2004-12-12"></td>
   </tr>
</table>
<br>

<table>
   <tr>
      <input type="hidden" name="campaignDTO[1].ein"value="EIN1">
      <td>EIN1</td>
      <td>Start Date</td>
      <td><input type="text" name="campaignDTO[1].startDate" maxlength="10"
          size="10" value="2003-01-01"></td>
   </tr>
   <tr>
      <td>
      <!-- other HTML appears here -->
      </td>
      <td>End Date</td>
      <td><input type="text" name="campaignDTO[1].endDate" maxlength="10"
          size="10" value="2003-12-31"></td>
   </tr>
</table>
<br>
 

For the preceding logic to work correctly, we need the following ActionForm definition.

public class ManageCampaignsForm extends ValidatorForm implements
    Serializable {
    public ManageCampaignsForm() {
    }
    public String getEin() {
        return ein;
    }
    public void setEin( String ein ) {
        this.ein = ein;
    }
    public String getStartDate() {
        return startDate;
    }
    public void setStartDate( String startDate ) {
        this.startDate = startDate;
    }
    public String getEndDate() {
        return endDate;
    }
    public void setEndDate( String endDate ) {
        this.endDate = endDate;
    }
    /** Coarse grained DTO is provided by the service layer */
    public void setCampaigns( List campaigns ) {
        this.campaigns = campaigns;
    }
    /** Coarse grained DTO is provided to the service layer */
    public List getCampaigns() {
        return campaigns;
    }
    private String ein;
    private String startDate;
    private String endDate;
    private List campaigns;
    /* The identifier CampaignDTO specified in the <iterate> tag is used to get
    the appropriate element from the underlying Collection campaigns */
    public CampaignDTO getCampaignDTO( int index ) {
        return ( CampaignDTO )campaigns.get( index );
    }
}
 

The nested property can nest to any number of levels, using both indexed and non-indexed properties. Chapter 5 implements the use case Update Campaigns that employs simple and indexed properties in a nested combination.

Custom Extensions with Plug-Ins

A framework must provide a facility for creating custom extensions by allowing a mechanism for plugging external services seamlessly into the framework. This implies that the framework must provide extension points, using which the life cycle management (i.e., init() and destroy()) of the pluggable component is possible. By providing such extension points, a developer can write a service that conforms to the interface supported by the extension mechanism, in this case the PlugIn interface, for controlling the creation, usage, and cleanup of the service and its corresponding resources within the context of the framework.

The Struts Validator is an example of a plug-in that enables declarative form validation. The corresponding entry in struts-config.xml is depicted here:

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
   <set-property property="pathnames"
                 value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
 

The ValidatorPlugIn class, and all other plug-in classes, are instantiated by the controller during its initialization. Each plug-in object is instantiated using the className attribute in the <plug-in> element. This plug-in object adheres to the design patterns of JavaBeans specification by providing the property accessor methods for each property specified in the <plug-in> element. Once a plug-in is instantiated, its init method is called to enable the developer to perform plug-in–specific initialization. For example, the ValidatorPlugIn.init method will initialize its resources and save the resources in the ServletContext using ValidatorPlugIn.VALIDATOR_KEY; these resources are subsequently used for creating an instance of the class org.apache.commons.validator.Validator in the context of the framework. The plug-in(s) instantiated by the controller are saved in the ServletContext as an array of org.apache.struts.action.PlugIn objects using the key Action.PLUG_INS_KEY. This array is subsequently used by the controller's destroy() method to call the destroy method on each plug-in for releasing acquired resources. Plug-in usage provides an elegant solution for initializing and saving objects that provide a specific set of services and whose usage can augment the functionality of the framework.