Now that we understand how to constrUCt the Model and View components of your application, it is time to focus on the Controller
components. Struts includes a servlet that implements the PRimary function of mapping a request URI to an Action
class. Therefore, your primary responsibilities related to the Controller are:
ActionForm
class to mediate between the Model and the View. (See also Building an ActionForm). Action
class for each logical request that may be received (extend org.apache.struts.action.Action
). struts-config.xml
. To deploy your application, you will also need to:
The latter two items are covered in the "Configuring Applications" chapter.
For those of you familiar with MVC architecture, the ActionServlet represents the C - the controller. The job of the controller is to:
The Struts controller delegates most of this grunt work to the Request Processor and Action classes.
In addition to being the front controller for your application, the ActionServlet instance also is responsible for initialization and clean-up of resources. When the controller initializes, it first loads the application config corresponding to the "config" init-param. It then goes through an enumeration of all init-param
elements, looking for those elements who's name starts with config/
. For each of these elements, Struts loads the configuration file specified by the value of that init-param
, and assigns a "prefix" value to that module's ModuleConfig instance consisting of the piece of the init-param
name following "config/". For example, the module prefix specified by the init-param config/foo
would be "foo". This is important to know, since this is how the controller determines which module will be given control of processing the request. To access the module foo, you would use a URL like:
http://localhost:8080/myApp/foo/someAction.do
For each request made of the controller, the method process(HttpServletRequest, HttpServletResponse)
will be called. This method simply determines which module should service the request and then invokes that module's RequestProcessor's process method, passing the same request and response.
The RequestProcessor is where the majority of the core processing occurs for each request. Let's take a look at the helper functions the process method invokes in-turn:
processPath
Determine the path that invoked us. This will be used later to retrieve an ActionMapping. processLocale
Select a locale for this request, if one hasn't already been selected, and place it in the request. processContent
Set the default content type (with optional character encoding) for all responses if requested. processNoCache
If appropriate, set the following response headers: "Pragma", "Cache-Control", and "EXPires". processPreprocess
This is one of the "hooks" the RequestProcessor makes available for subclasses to override. The default implementation simply returns true
. If you subclass RequestProcessor and override processPreprocess you should either return true
(indicating process should continue processing the request) or false
(indicating you have handled the request and the process should return) processMapping
Determine the ActionMapping associated with this path. processRoles
If the mapping has a role associated with it, ensure the requesting user is has the specified role. If they do not, raise an error and stop processing of the request. processActionForm
Instantiate (if necessary) the ActionForm associated with this mapping (if any) and place it into the appropriate scope. processPopulate
Populate the ActionForm associated with this request, if any. processValidate
Perform validation (if requested) on the ActionForm associated with this request (if any). processForward
If this mapping represents a forward, forward to the path specified by the mapping. processInclude
If this mapping represents an include, include the result of invoking the path in this request. processActionCreate
Instantiate an instance of the class specified by the current ActionMapping (if necessary). processActionPerform
This is the point at which your action's perform
or execute
method will be called. processForwardConfig
Finally, the process method of the RequestProcessor takes the ActionForward returned by your Action class, and uses to select the next resource (if any). Most often the ActionForward leads to the presentation page that renders the response. An ActionForm represents an Html form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. ActionForms can be stored in either the session (default) or request scopes. If they're in the session it's important to implement the form's reset
method to initialize the form before each use. Struts sets the ActionForm's properties from the request parameters and sends the validated form to the appropriate Action's execute
method.
When you code your ActionForm
beans, keep the following principles in mind:
ActionForm
class itself requires no specific methods to be implemented. It is used to identify the role these particular beans play in the overall architecture. Typically, an ActionForm
bean will have only property getter and property setter methods, with no business logic. getXxx
and setXxx
methods) for each field that is present in the form. The field name and property name must match according to the usual javaBeans conventions (see the Javadoc for the java.beans.Introspector
class for a start on information about this). For example, an input field named username
will cause the setUsername
method to be called. validate
method to ensure all required properties are present, and that they contain reasonable values. An ActionForm that fails validation will not even be presented to the Action for handling. customer.getName()
and customer.setName(string Name)
on your customer bean. See the Tag Library Developer Guides for more about using nested syntax with the Struts jsp tags. Maintaining a separate concrete ActionForm class for each form in your Struts application is time-consuming. It is particularly frustrating when all the ActionForm does is gather and validate simple properties that are passed along to a business JavaBean.
This bottleneck can be alleviated through the use of DynaActionForm classes. Instead of creating a new ActionForm subclass and new get/set methods for each of your bean's properties, you can list its properties, type, and defaults in the Struts configuration file.
For example, add the following to struts-config.xml for a UserForm bean that stores a user's given and family names:
<form-bean name="UserForm" type="org.apache.struts.action.DynaActionForm"> <form-property name="givenName" type="java.lang.String" initial="John"/> <form-property name="familyName" type="java.lang.String" initial="Smith"/></form-bean>
The types supported by DynaActionForm include:
You may also specify Arrays of these types (e.g. String[]
). You may also specify a concrete implementation of the Map Interface, such as java.util.HashMap
, or a List implementation, such as java.util.ArrayList
.
If you do not supply an initial attribute, numbers will be initialized to 0 and objects to null
.
In JSP pages using the original Struts custom tags, attributes of DynaActionForm
objects can be referenced just like ordinary ActionForm
objects. Wherever a Struts tag refers to a "property", the tags will automatically use the DynaActionForm properties just like those of a conventional JavaBean. You can even expose DynaActionForm properties using bean:define. (Although, tou can't use bean:define to instantiate a DynaActionForm, since it needs to be setup with the appropriate dyna-properties).
If you are using the Struts JSTL EL taglib, the references are different, however. Only properties of ordinary ActionForm
objects can be directly accessed through the JSTL expression language syntax. The DynaActionForm
properties must be accessed through a slightly different syntax. The JSTL EL syntax for referencing a property of an ActionForm
goes like this:
${formbean.prop}
The syntax for referencing a property of a DynaActionForm
would be:
${dynabean.map.prop}
The map
property is a property of DynaActionForm
which represents the HashMap
containing the DynaActionForm
properties.
DynaActionForms are meant as an easy solution to a common problem: Your ActionForms use simple properties and standard validations, and you just pass these properties over to another JavaBean (say using BeanUtils.copyProperties(myBusinessBean,form)
).
DynaActionForms are not a drop-in replacement for ActionForms. If you need to access ActionForm properties in your Action, you will need to use the map-style accessor, like myForm.get("name")
. If you actively use the ActionForm object in your Action, then you may want to use conventional ActionForms instead.
DynaActionForms cannot be instantiated using a no-argument constructor. In order to simulate the extra properties, there is a lot of machinery involved in their construction. You must rely on Struts to instantiate a DynaActionForm for you, via the ActionMapping.
If need be, you can extend the DynaActionForm to add custom validate and reset methods you might need. Simply specify your subclass in the struts-config instead. However, you cannot mix conventional properties and DynaProperties. A conventional getter or setter on a DynaActionForm won't be found by the reflection utilities.
To use DynaActionForms with the Struts Validator, specify org.apache.struts.validator.ValidatorActionForm
(or your subclass) as the form-bean class.
And, of course, while the DynaActionForm may support various binary types, properties used with the html:text
tag should still be String properties.
DynaActionForms relieve developers of maintaining simple ActionForms. For even less maintenance, try Niall Pemberton's LazyActionForm.
The DynaActionForm classes offer the ability to create ActionForm beans at initialization time, based on a list of properties enumerated in the Struts configuration file. However, many HTML forms are generated dynamically at request time. Since the properties of these forms' ActionForm beans are not all known ahead of time, we need a new approach.
Struts allows you to make one or more of your ActionForm's properties' values a Map instead of a traditional atomic object. You can then store the data from your form's dynamic fields in that Map. Here is an example of a map-backed ActionForm class:
public FooForm extends ActionForm { private final Map values = new HashMap(); public void setValue(String key, Object value) { values.put(key, value); } public Object getValue(String key) { return values.get(key); }}
In its corresponding JSP page, you can access objects stored in the values map using a special notation: mapname(keyname)
. The parentheses in the bean property name indicate that:
mapname
is indexed using Strings (probably backed by a Map), and that keyname
value from the parentheses when it calls the get/set methods. Here is a simple example:
<html:text property="value(foo)"/>
This will call the getValue
method on FooForm with a key value of "foo
" to find the property value. To create a form with dynamic field names, you could do the following:
<% for (int i = 0; i < 10; i++) { String name = "value(foo-" + i + ")";%> <html:text property="<%= name %>"/> <br/><% }%>
Note that there is nothing special about the name value
. Your map-backed property could instead be named property
, thingy
, or any other bean property name you prefer. You can even have multiple map-backed properties on the same bean.
In addition to map-backed properties, you can also create list-backed properties. You do so by creating indexed get/set methods on your bean:
public FooForm extends ActionForm { private final List values = new ArrayList(); public void setValue(int key, Object value) { values.set(key, value); } public Object getValue(int key) { return values.get(key); }}
In your presentation pages, you access individual entries in a list-backed property by using a different special notation: listname[index]
. The braces in the bean property name indicate that the bean property named listname
is indexed (probably backed by a List), and that Struts should look for get/set methods that take an index parameter in order to find the correct sub-property value.
While map-backed ActionForms provide you with more flexibility, they do not support the same range of syntax available to conventional or DynaActionForms. You might have difficulty referencing indexed or mapped properties using a map-backed ActionForm. The validwhen
validator (since Struts 1.2.1) also does not support map-backed ActionForms.
The Action
class defines two methods that could be executed depending on your servlet environment:
public ActionForward execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response)throws Exception;public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception;
Since the majority of Struts projects are focused on building web applications, most projects will only use the "HttpServletRequest" version. A non-HTTP execute() method has been provided for applications that are not specifically geared towards the HTTP protocol.
The goal of an Action
class is to process a request, via its execute
method, and return an ActionForward
object that identifies where control should be forwarded (e.g. a JSP, Tile definition, Velocity template, or another Action) to provide the appropriate response. In the MVC/Model 2 design pattern, a typical Action
class will often implement logic like the following in its execute
method:
Action
class finds that no logon exists, the request can be forwarded to the presentation page that displays the username and passWord prompts for logging on. This could occur because a user tried to enter an application "in the middle" (say, from a bookmark), or because the session has timed out, and the servlet container created a new one. Action
class itself, but should generally be performed by calling an appropriate method of a business logic bean. ActionForward
object that identifies the presentation page to be used to generate this response, based on the newly updated beans. Typically, you will acquire a reference to such an object by calling findForward
on either the ActionMapping
object you received (if you are using a logical name local to this mapping), or on the controller servlet itself (if you are using a logical name global to the application). In Struts 1.0, Actions called a perform
method instead of the now-preferred execute
method. These methods use the same parameters and differ only in which exceptions they throw. The elder perform
method throws SerlvetException
and IOException
. The new execute
method simply throws Exception
. The change was to facilitate the Declarative Exception handling feature introduced in Struts 1.1.
The perform
method may still be used in Struts 1.1 but is deprecated. The Struts 1.1 method simply calls the new execute
method and wraps any Exception
thrown as a ServletException
.
Remember the following design guidelines when coding Action
classes:
Action
class, and uses this one instance to service all requests. Thus, you need to write thread-safe Action
classes. Follow the same guidelines you would use to write thread-safe Servlets. Here are two general guidelines that will help you write scalable, thread-safe Action classes: Action
class. Local variables are created on a stack that is assigned (by your JVM) to each request thread, so there is no need to worry about sharing them. An Action
can be factored into several local methods, so long as all variables needed are passed as method parameters. This assures thread safety, as the JVM handles such variables internally using the call stack which is associated with a single Thread. Action
class. If your application specific code throws expections you should catch these exceptions in your Action class, log them in your application's log (servlet.log("Error message", exception)
) and return the appropriate ActionForward. It is wise to avoid creating lengthy and complex Action classes. If you start to embed too much logic in the Action
class itself, you will begin to find the Action
class hard to understand, maintain, and impossible to reuse. Rather than creating overly complex Action classes, it is generally a good practice to move most of the persistence, and "business logic" to a separate application layer. When an Action class becomes lengthy and procedural, it may be a good time to refactor your application architecture and move some of this logic to another conceptual layer; otherwise, you may be left with an inflexible application which can only be accessed in a web-application environment. Struts should be viewed as simply the foundation for implementing MVC in your applications. Struts provides you with a useful control layer, but it is not a fully featured platform for building MVC applications, soup to nuts.
The MailReader example application included with Struts stretches this design principle somewhat, because the business logic itself is embedded in the Action
classes. This 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. In order to demonstrate, in simple terms, the different ways Struts can be used, the MailReader application does not always follow best practices.
You can define an ExceptionHandler to execute when an Action's execute
method throws an Exception. First, you need to subclass org.apache.struts.action.ExceptionHandler
and override the execute
method. Your execute
method should process the Exception and return an ActionForward object to tell Struts where to forward to next. Then you configure your handler in struts-config.xml like this:
<global-exceptions> <exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/></global-exceptions>
This configuration element says that com.yourcorp.ExceptionHandler.execute
will be called when any IOException is thrown by an Action. The key
is a key into your message resources properties file that can be used to retrieve an error message.
You can override global exception handlers by defining a handler inside an action definition.
A common use of ExceptionHandlers is to configure one for java.lang.Exception
so it's called for any exception and log the exception to some data store.
The PlugIn interface extends Action and so that applications can easily hook into the ActionServlet lifecycle. This interface defines two methods, init()
and destroy()
, which are called at application startup and shutdown, respectively. A common use of a Plugin Action is to configure or load application-specific data as the web application is starting up.
At runtime, any resource setup by init
would be accessed by Actions or business tier classes. The PlugIn interface allows you to setup resources, but does not provide any special way to access them. Most often, the resource would be stored in application context, under a known key, where other components can find it.
PlugIns are configured using <plug-in> elements within the Struts configuration file. See PlugIn Configuration for details.
In order to Operate successfully, the Struts controller servlet needs to know several things about how each request URI should be mapped to an appropriate Action
class. The required knowledge has been encapsulated in a Java class named ActionMapping, the most important properties are as follows:
type
- Fully qualified Java class name of the Action implementation class used by this mapping. name
- The name of the form bean defined in the config file that this action will use. path
- The request URI path that is matched to select this mapping. See below for examples of how matching works and how to use wildcards to match multiple request URIs. unknown
- Set to true
if this action should be configured as the default for this application, to handle all requests not handled by another action. Only one action can be defined as a default within a single application. validate
- Set to true
if the validate
method of the action associated with this mapping should be called. forward
- The request URI path to which control is passed when this mapping is invoked. This is an alternative to declaring a type
property. How does the controller servlet learn about the mappings you want? It would be possible (but tedious) to write a small Java class that simply instantiated new ActionMapping
instances, and called all of the appropriate setter methods. To make this process easier, Struts uses the Jakarta Commons Digester component to parse an XML-based description of the desired mappings and create the appropriate objects initialized to the appropriate default values. See the Jakarta Commons website for more information about the Digester.
The developer's responsibility is to create an XML file named struts-config.xml
and place it in the WEB-INF Directory of your application. This format of this document is described by the Document Type Definition (DTD) maintained at http://struts.apache.org/dtds/struts-config_1_2.dtd. This chapter covers the configuration elements that you will typically write as part of developing your application. There are several other elements that can be placed in the struts-config file to customize your application. See "Configuring Applications" for more about the other elements in the Struts configuration file.
The controller uses an internal copy of this document to parse the configuration; an Internet connection is not required for operation.
The outermost XML element must be <struts-config>
. Inside of the <struts-config> element, there are three important elements that are used to describe your actions:
<form-beans>
<global-forwards>
<action-mappings>
<form-beans>
新闻热点
疑难解答