Vous êtes sur la page 1sur 20

Struts – Advanced Actions

Struts and the Controller Layer .............................................................................................................................. 1


Action ..................................................................................................................................................................... 2
DispatchAction ....................................................................................................................................................... 3
DownloadAction .................................................................................................................................................... 5
ForwardAction........................................................................................................................................................ 6
IncludeAction ......................................................................................................................................................... 8
LocaleAction .......................................................................................................................................................... 9
LookupDispatchAction......................................................................................................................................... 10
MappingDispatchAction....................................................................................................................................... 13
SwitchAction ........................................................................................................................................................ 15
PropertyUtils ........................................................................................................................................................ 16
Global Forwards ................................................................................................................................................... 17
Struts Modules...................................................................................................................................................... 18
Struts and the Controller Layer

Struts has a servlet called the ActionServlet. The ActionServlet inspects the incoming request, provides appropriate attributes such
as Message Resource Bundles, and delegates the request to an action based on the incoming request path. The object that relates
the action to the incoming request path is the Action Mapping. That is, in Struts, ActionServlet and Action classes together form
the controller. They are supposed to select and dispatch to the next view.

Action classes are defined to handle requests and are where your presentation logic resides. Actions exist between the Model and
View of an application.

The struts-config.xml file designates the Action classes that handle requests for various URLs. The Action objects do:
z Invoke the appropriate business
z Data-access logic
z Store the results in beans
z Designate the type of situation (missing data, database error etc.)

The struts-config.xml file then decides which JSP page should apply to that situation. Generally Actions do:
z Invoke business rules
z Return Model objects to the View to display

Actions also prepare error messages to display in the View. You can also create utility actions. Utility actions can be linked to other
actions using action chaining. This allows you to extend the behavior of an action without changing an action or having deeply
nested class hierarchies of actions.

The Actions provided by Struts are DispatchAction, DownloadAction ForwardAction, IncludeAction, LocaleAction,
LookupDispatchAction, MappingDispatchAction, and SwitchAction. All these classes are defined in org.apache.struts.actions
package.

1
Action

1. Create an action by subclassing org.apache.struts.action.Action and Override the execute() method


import org.apache.struts.actions.Action;
...
public class MyAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws ServletException {
/* invokes business logic and data-access logic */
return mapping.findForward("success");
}
}
The Action Mapping contains everything configurable in the action element of the Struts config file. The ActionForm represents
the incoming request parameters. The HttpServletRequest references the current request object. No compulsory use for
HttpServletResponse. The execute() method returns an ActionForward. The ActionForward is the logical next View or the
logical next step.
2. Configure the Action in the Struts config file.
<action-mappings>
<action path="/MyAction"
type="myco.myapp.struts.MyAction"
<forward name="success" path="/WEB-INF/results/success-blah.jsp"/>...
</action>
</action-mappings>
The path attribute specifies the incoming request path that this action will handle.

2
DispatchAction
It is an abstract Action that provides mechanism to collect related functions into a single action and eliminates the need
of creating multiple independent actions for each function, and dispatches to a public method that is named by the request
parameter on the request URL whose name is specified by the parameter property of the corresponding ActionMapping. This
Action is useful for developers who prefer to combine many similar actions into a single Action class, in order to simplify their
application design.

Rather than having a single execute() method, DispatchAction provides a method for each logical action. The DispatchAction
dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request
parameter. The value of the incoming request parameter is the name of the method that the DispatchAction will invoke.

For example, consider a set of related functions for inserting a user, updating a user, and deleting a user. Instead of creating an
InsertUserAction class, an UpdateUserAction class, and a DeleteUserAction class, by extending DispatchAction, you can create
one UserAction class that has three methods: insert(), update(), and delete(). At run time, DispatchAction manages routing requests
to the appropriate method in its subclass. DispatchAction determines which method to call based on the value of a request parameter
that is passed to it from the incoming request. In addition, If the value of the request parameter is empty, a method named
unspecified is called. The default action is to throw an exception. If the request was cancelled, the custom handler cancelled,
will be used instead.

Since DispatchAction is an abstract Action, the value of the parameter attribute of the action mapping is used to pick the appropriate
execute() method, which must have the same signature of the standard Action.execute() method.

To use DispatchAction, you must create a subclass from it and provide a set of methods that will be called to process requests.
Additionally, you have to set up for the action an action mapping that specifies the name of a request parameter that will be used to
select which method should be called for each request.

Original:

Applied:
1. Create an action handler class that subclasses DispatchAction and a method to represent each logical related action:
import org.apache.struts.actions.DispatchAction;
...
public class MyDispatchAction extends DispatchAction{
/* No execute() - DispatchAction provides an implementation of execute() method that manages delegating to the individual methods
*/
/* No getKeyMethodMap() */

public ActionForward insert(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
//code for inserting users here.
return mapping.findForward("success");
}

public ActionForward update(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
//code for updating users here.
return mapping.findForward("success");
}

public ActionForward delete(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
//code for deleting users here.
return mapping.findForward("success");
}

public ActionForward unspecified(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward("page-not-found");
}

public ActionForward cancelled(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward("main-page");
}
}
2. Create an Action Mapping for this action handler using the parameter attribute to specify the request parameter that

3
carries the name of the method will be invoked:
<action-mappings>
<action path="/MyHandler"
type="myco.myapp.struts.MyDispatchAction"
parameter="command"
<!-- useing the value of the request parameter named "command" to pick the appropriate "execute" method, which
must have the same signature of the standard Action.execute method. -->
...
</action>
</action-mappings>
3. Pass the action a request parameter that refers to the method will be invoked:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<a href="MyHandler.do?command=insert&id=007">Insert User</a>
<a href="MyHandler.do?command=update&id=007">Update User</a></html:form>
<a href="MyHandler.do?command=delete&id=007">Delete User</a></html:form>
</body>
</html:html>

4
DownloadAction
DownloadAction subclass simplifies downloading data to a web client. This data might be dynamically generated by your
webapp or a static file on the server.

Original:
...

Applied:
1. Create an action handler class that subclasses DownloadAction and a method to represent each logical related action, and
implement the StreamInfo() method to get data and content type:
package com.myco.myapp.struts;
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.DownloadAction;

public class MyDownloadAction extends DownloadAction{


protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
/* Get InputStream somehow, as a result of processing request */
InputStream input = ...;
/* Similarly get content type */
String contentType = ...;

return new StreamInfo{


public InputStream getInputStream(){ return input; }
public String getContentType(){ return contentType; }
}
}
}
2. Create an Action Mapping for this action handler:
<action-mappings>
<action path="/MyFileDownloadHandler"
form="MyDataForm"
type="com.myco.myapp.struts.MyDownloadAction">
/* Do not specify a <forward> */
</action>
</action-mappings>

5
ForwardAction
It enables to forward request to the context-relative URI specified by the parameter property of the associated ActionMapping.
This can be used to integrate Struts with other business logic components that are implemented as legacy servlets or JSP pages,
but still take advantage of the Struts controller servlet's functionality such as processing of form beans. If form beans will be
processed, they need to extend ActionForm and are declared in struts-config.xml.

ForwardAction is provided as a simple utility action that can be used for scenarios in which you simply want to link to a JSP page, or
when the legacy code needs to write header or cookie information in order to work correctly. ForwardAction can be used to create
links to JSPs so that you don’t have to create an action whose only responsibility is to forward a request every time you want to link to
a JSP. It follows the MVC principles that all requests are supposed to be routed through the Controller by not linking directly to the
JSP. With ForwardAction, you simply create an action mapping in the Struts configuration file and specify the location to which the
action will forward.

To use ForwardAction, simply create action mapping entries in the Struts configuration file. In general, the ForwardAction’s
parameter attribute specifies the resource to be forwarded to.

Original:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<a href="/WEB-INF/classes/com/myco/myapp/MyLoginServlet">Login</a>
<html:link page="/WEB-INF/classes/com/myco/myapp/MyLoginServlet">Login</html:link>
</body>
</html:html>

Applied:
1. Create an Action Mapping in the Struts configuration file that uses the ForwardAction with the parameter attribute to
specify the Servlet/JSP path:
<action-mappings>
<action path="/Login"
type="org.apache.struts.actions.ForwardAction"
name="LoginForm"
validate="true"
input="/login.jsp"
parameter="/WEB-INF/classes/com/myco/myapp/MyLoginServlet">
/* Do not specify a <forward> */
</action>
</action-mappings>
2. Using the html:link tag with the action/page attribute, add a link to the JSP page that points to the action:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<html:link action="/Login">Login</html:link>
<html:link page="/Login.do">Login</html:link>
</body>
</html:html>

OR

From a design perspective this seems to be the best way of using the <html:link> tag since the link is completely decoupled from the
associated ActionMapping, thanks to the global-forward.

Applied:
1. Create a Global Forward and an Action Mapping in the Struts configuration file that uses the ForwardAction with the
parameter attribute to specify the Servlet/JSP path:
<global-forwards>
<forward name="LoginForward" path="/Login.do" />
</global-forwards>

6
<action-mappings>
<action path="/Login"
type="org.apache.struts.actions.ForwardAction"
name="LoginForm"
validate="true"
input="/login.jsp"
parameter="/WEB-INF/classes/com/myco/myapp/MyLoginServlet">
/* Do not specify a <forward> */
</action>
</action-mappings>
2. Using the html:link tag with the forward attribute, add a link to the JSP page that points to the action:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<html:link forward="LoginForward">Login</html:link>
</body>
</html:html>

7
IncludeAction
It enables to forward request to the context-relative URI specified by the parameter property of the associated ActionMapping.
This can be used to integrate Struts with other business logic components that are implemented as legacy servlets or JSP pages,
but still take advantage of the Struts controller servlet's functionality such as processing of form beans. If form beans will be
processed, they need to extend ActionForm and are declared in struts-config.xml.

IncludeAction behaves similarly to ForwardAction, but instead of forwarding to the specified URL, the specified URL is included.
This action is useful when you want to include the contents of one page in another, or when data needs to be written to the client after
the legacy code has sent its output.

To use IncludeAction, just create action mapping entries in the Struts configuration file. The parameter attribute indicates the actual
resource that has to be included in the response.

Original:
<jsp:include page="WEB-INF/classes/com/myco/myapp/MyLoginServlet" />

Applied:
1. Create an Action Mapping in the Struts configuration file that uses the IncludeAction with the parameter attribute to
specify the Servlet/JSP path:
<action-mappings>
<action path="/Login"
type="org.apache.struts.actions.IncludeAction"
name="LoginForm"
validate="true"
input="/login.jsp"
parameter="/WEB-INF/classes/com/myco/myapp/MyLoginServlet">
/* Do not specify a <forward> */
</action>
</action-mappings>

The difference between the IncludeAction and the ForwardAction is that we need to use the IncludeAction only if the action is
going to be included by another action or JSP.

The action could not use a ForwardAction because it would forward control to the new action rather than including its output within
the output of the JSP-or throw a nasty IllegalStateException if the output buffer was already committed.

8
LocaleAction
It provides mechanism to set a user's locale and further forwarding that to a specified page.

LocaleAction provides a convenient mechanism for changing a user’s locale. For example, consider a site that is offered in English
and Japanese versions. LocaleAction can be used to offer users a way to switch between the two languages without having to change
their browser settings. With LocaleAction you simply create an action mapping and then link to the action, specifying request
parameters for which locale to switch to and a page to forward after the locale has been switched.

To use LocaleAction, you must create an action mapping entry for it in the Struts configuration file and then link to the action,
specifying locale information and a page to forward to after the locale has been set.

Original:
...

Applied:
1. Create Form Beans and Action Mappings in the Struts configuration file that uses the LocaleAction:
<form-beans>
<form-bean name="English"
type="org.apache.struts.action.DynaActionForm">
<form-property name="language" type="String" initial="en" />
<form-property name="country" type="String" initial="US" />
</form-bean>
<form-bean name="Japanese"
type="org.apache.struts.action.DynaActionForm">
<form-property name="language" type="String" initial="jp" />
</form-bean>
... //other form beans
</form-beans>

<action-mappings>
<action path="/ToEnglish"
name="English"
type="org.apache.struts.actions.LocaleAction">
<forward name="success" path="/mystartpage.jsp" />
</action>
<action path="/ToJapanese"
name="Japanese"
type="org.apache.struts.actions.LocaleAction">
<forward name="success" path="/mystartpage.jsp" />
</action>
... //other form handlers
</action-mappings>
2. Using the html:link tag with the action attribute, add a link to the JSP page that points to the action:
<html:link action="/ToJapanese">
<bean:message key="prompt.to.japanese" />
</html:link>
<html:link action="/ToEnglish" >
<bean:message key="prompt.to.english" />
</html:link>

9
LookupDispatchAction
It is an abstract Action (a subclass of DispatchAction) that provides mechanism to combine many similar actions into a single
action class to simplify the application design, and dispatches to the subclass mapped execute method. Java MAP class is used
to dispatch methods. LookupDispatchAction is an elegant alternative to using hidden fields for handling forms with multiple
actions or multiple submit buttons with the same name, where the button name is specified by the parameter property of the
corresponding ActionMapping. It’s also a more robust alternative since it does not depend on JavaScript being enabled on the
client’s machine. Use this if for any reason you don’t want to define multiple form handlers (e.g., to make struts-config.xml
more manageable), or in the situations that DispatchAction can not resolved (e.g., I18N applications where button labels come
from properties file).

For example, consider a set of related functions for inserting a user, updating a user, and deleting a user. Instead of creating an
InsertUserAction class, an UpdateUserAction class, and a DeleteUserAction class, by extending MappingDispatchAction, you
can create one UserAction class that has three methods: insert(), update(), and delete(). At run time, LookupDispatchAction
manages routing requests to the appropriate method in its subclass. LookupDispatchAction determines which method to route to
based on the value of a request parameter being passed to it from the incoming request. LookupDispatchAction uses the value of the
request parameter to reverse-map to a property in the Struts resource bundle file, ApplicationResources.properties. That is, the
value of the request parameter is compared against the values of properties in the resource bundle until a match is found. The key for
the matching property is then used as a key to another map that maps to a method in your LookupDispatchAction subclass that will
be executed.

To use LookupDispatchAction, you must create a subclass from it and provide a set of methods that will be called to process requests.
The subclass must also include a getKeyMethodMap() method that maps methods in the class to keys in the Struts resource bundle
file. Additionally, you have to set up for the action an action mapping that specifies the name of a request parameter that will be used
to select which method will be called for each request. In the following example, the LookupDispatchAction inspects the label of the
button called action. The label will be looked up from the resource bundle, the corresponding key will be found, and the key will be
used against the method map to find the name of the method to invoke essentially.

Original:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>
<script language="JavaScript">
function changeMode(formName, src){
document.forms[formName].elements["mode"].value = src;
}
</script>
</head>
<body>
<html:form action="MyFormHandler.do">
//... other fields on the form, omitted
<html:hidden property="mode" value="unknown"/>
<html:submit value="Insert User" onclick="changeMode('MyFormBean','insert')" />
<html:submit value="Update User" onclick="changeMode('MyFormBean','update')" />
<html:submit value="Delete User" onclick="changeMode('MyFormBean','delete')" />
</html:form>
</body>
</html:html>

Only one form handler:

Applied:
1. Create an action handler class that subclasses LookupDispatchAction, a method to represent each logical related action,
and implement the getKeyMethodMap() method to map the resource keys to method names:
import org.apache.struts.actions.LookupDispatchAction;
...
public class MyLookupDispatchAction extends LookupDispatchAction{
/* No execute() - DispatchAction provides an implementation of execute() method that manages delegating to the individual methods
*/
/* getKeyMethodMap() is required by LookupDispatchAction subclasses and is used to map the names of keys in the Struts resource
bundle file to methods in the class. */

protected Map getKeyMethodMap(){


HashMap map = new HashMap();
map.put("myapp.submit.button.insert", "insert");
map.put("myapp.submit.button.update", "update");

10
map.put("myapp.submit.button.delete", "delete");
return map;
}

public ActionForward insert(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws IOException, ervletException {
//code to insert here and remember to return the "next" page.
return mapping.findForward("success");
}

public ActionForward update(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
//code to update here remember to return the "next" page
return mapping.findForward("success");
}

public ActionForward delete(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
//code to delete here remember to return the "next" page.
return mapping.findForward("success");
}

public ActionForward unspecified(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward("page-not-found");
}

public ActionForward cancelled(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward("main-page");
}
}
2. Create an Action Mapping for this action handler using the parameter attribute to specify the request parameter, and
then using value of the request parameter to locate the corresponding key in ApplicationResources, in turn, using
matched key to find the name of the method to invoke:
<action-mappings>
<action path="/MyFormHandler"
type="myco.myapp.struts.MyLookupDispatchAction"
parameter="action"
...
</action>
</action-mappings>
3. Set up the messages in the resource bundle, e.g. ApplicationResources.properties for the labels and values of the buttons:
myapp.submit.button.insert=Insert User
myapp.submit.button.update=Update User
myapp.submit.button.delete=Delete User
4. Use the bean:message tag to display the labels of the button and associate the buttons with the name action:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<html:form action="MyFormHandler.do">
... // form properties here
<html:submit property="action">
<bean:message key="myapp.submit.button.insert" /> <!-- Display Insert User -->
</html:submit>
<html:submit property="action">
<bean:message key="myapp.submit.button.update" /> <!-- Display Update User -->
</html:submit>
<html:submit property="action">
<bean:message key="myapp.submit.button.delete" /> <!-- Display Delete User -->
</html:submit>
</html:form>
</body>

11
</html:html>

12
MappingDispatchAction
It lets you combine many related actions into a single action class and manage through creating multiple action-mappings. Use
this when you want to define multiple form handlers for the same Action.

MappingDispatchAction is a subclass of DispatchAction. The MappingDispatch Action class provides a mechanism for
modularizing a set of related functions into a single action, eliminating the need to create separate, independent actions for each
function. For example, consider a set of related functions for adding a user, updating a user, and removing a user. Instead of creating
an InsertUserAction class, an Update UserAction class, and a ReleteUserAction class, by extending MappingDispatchAction,
you can create one UserAction class that has three methods: insert(), update(), and delete(). At run time, MappingDispatchAction
manages routing requests to the appropriate method in its subclass. MappingDispatchAction determines which method to route to
based on the value of a parameter being passed to it from an action mapping in the Struts configuration file.

To use MappingDispatchAction, you must create a subclass from it and provide a set of methods that will be called to process
requests. Additionally, you must set up action mappings that specify which method will be called for each request.

Original:

Multiple form handlers:

Applied:
1. Create an action handler class that subclasses MappingDispatchAction, a method to represent each logical related action:
import org.apache.struts.actions.MappingDispatchAction;
...
public class MyMappingDispatchAction extends MappingDispatchAction{
/* No execute() - DispatchAction provides an implementation of execute() method that manages delegating to the individual methods
*/

public ActionForward insert(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
//code for inserting user here.
return mapping.findForward("success");
}

public ActionForward update(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
//code for updating user here.
return mapping.findForward("success");
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
//code for deleting here.
return mapping.findForward("success");
}

public ActionForward unspecified(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward("page-not-found");
}

public ActionForward cancelled(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward("main-page");
}
}
2. Create an Action Mapping for this action handler using the parameter attribute to specify the request parameter that
carries the name of the method will be invoked:
<!-- The value specified with the parameter attribute must match the name of a method in your MappingDispatchAction subclass. -->
<action-mappings>
<action path="/InsertUser"
type="myco.myapp.struts.MyMappingDispatchAction "
parameter="insert"
...
</action>
<action path="/UpdateUser"
type="myco.myapp.struts.MyMappingDispatchAction "
parameter="update"
13
...
</action>
<action path="/DeleteUser"
type="myco.myapp.struts.MyMappingDispatchAction "
parameter="delete"
...
</action>
</action-mappings>

14
SwitchAction
It provides a mechanism to switch between modules and then forwards control to a URI (specified in a number of possible
ways) within the new module.

Struts enables you to modularize your Struts application. Each module has its own set of configuration data as well as its own request
processor. The SwitchAction class provides a mechanism for switching between modules in a modularized Struts application.
SwitchAction works similarly to ForwardAction, except that before forwarding to a specified resource, the action changes the
currently selected module. This is useful for forwarding to JSPs outside of the current module.

To use SwitchAction, you must create an action mapping entry for it in the Struts configuration file and then link to the action,
specifying the module to switch to and a page to forward to after the module has been switched. Remember, in web-xml file, any
init-param prefixed with “config/” is interpreted as configuration for a separate module. The two request parameters – prefix and page
stand for the module and the action mapping within that module:

z prefix - The module prefix (beginning with "/") of the module to which control should be switched. Use a zero-length string for
the default module. The appropriate ModuleConfig object will be stored as a request attribute, so any subsequent logic will
assume the new module.
z page - Module-relative URI (beginning with "/") to which control should be forwarded after switching.

In following example, this global-forward turn points to an action mapping called Switch.do and also adds two request parameters.
The Switch.do is the ActionMapping for the SwitchAction. In this case, the module is loanModule (identified by the
struts-config-loan.xml) and the listloans.do stands for an action mapping within the struts-config-loan.xml – the Struts Config file for
Loan module.

Original:
...

Applied:
1. Create a Action Mapping in the specified modularized Struts configuration file:
<!-- struts-config-load.xml -->
<action-mappings>
<action path="/listloans.do"
type="mybank.appl.ListLoanAction">
</action>
</action-mappings>
2. Create a Global Forward and an Action Mapping in the specified modularized Struts configuration file that uses the
SwitchAction:
<global-forwards>
<forward name="goto-loanModule"
path="/switch.do?page=/listloans.do&prefix=/loanModule" />
<!-- The page parameter specifies the module relative action and the prefix parameter specifies the prefix of the module.
-->
</global-forwards>

<action-mappings>
<action path="/switch"
type="org.apache.struts.actions.SwitchAction">
</action>
... //other form handlers
</action-mappings>
3. Using the html:link tag with the forward attribute, add a link to the JSP page that points to the action:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<html:link forward="goto-loanModule">Go to Loan Module</html:link>
</body>
</html:html>

15
PropertyUtils
Use PropertyUtils to read properties on JavaBeans in general, and ActionForms in particular, without resorting to type
conversions.

Original:
public class MyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
//get userid and password
RegistrationForm rForm = (RegistrationForm) form;
String userid = rForm.getUserId();
String password = rForm.getPassword();
...
}
}

Applied:
import org.apache.commons.beanutils.PropertyUtils;
...
public class MyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
//get userid and password
String userid = (String) PropertyUtils.getProperty(form,"userid");
String password = (String) PropertyUtils.getProperty(form,"password");
...
}
}

16
Global Forwards
Instead of hard-coding paths in your <html:link>s, you can use global forwards instead. The advantage with this approach is that
should you move a JSP or HTML page from one location to another, you don’t have to amend every link to that page. You only need
to change the global forward’s path. This greatly improves the maintainability of your webapp.

Original:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<a href="import.do">Import</a>
<a href="export.jsp">Export</a>
</body>
</html:html>

Applied:
1. Create Global Forwards to specify the common Servlet/JSP paths:
<global-forwards>
<forward name="import" path="/import.do"/>
<forward name="export" path="/export.jsp"/>
...
</global-forwards>
2. Using the html:link tag with the forward attribute, add a link to the JSP page that points to the action:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<html:link forward="import">Import</html:link >
<html:link forward="export">Export</html:link >
</body>
</html:html>

17
Struts Modules
Split up struts-config.xml for the reasons of Manageability, Separate namespaces, Source control. There is a Struts feature called
modules that allows you to split a Struts configuration files into different modules. A module represents a logical split in your webapp.
Each module gets its own namespace. In web-xml file, any init-param prefixed with “config/” is interpreted as configuration for a
separate module.

Here is a tip: Generally web applications are organized so that navigation occurs from generic to specific. For instance, you start from
the initial welcome page for the web application and then navigate to a specific module. You can organize you struts modules so that
the initial welcome page and other top-level pages are defined in the default application module (struts-config.xml). The pages
correspond to individual use cases are defined in different application modules (struts-config-xxx.xml). You can then navigate from
the default application module to the use case specific module.

In the following example, the init parameter “config” defines the default module, the init parameter “config/admin” defines the admin
module, and the init parameter “config/logon” defines the logon module respectively.

Original:

Applied:
1. Modify web.xml:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<!-- THE DEFAULT SUB-MODULE -->
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config-shared.xml, <!-- Using a Shared Struts Configuration File Across Submodules -->
/WEB-INF/struts-config.xml
</param-value>
</init-param>
<init-param>
<!-- THE "ADMIN" SUB-MODULE -->
<param-name>config/admin</param-name>
<param-value>
/WEB-INF/struts-config-shared.xml, <!-- Using a Shared Struts Configuration File Across Submodules -->
/WEB-INF/struts-config-admin.xml
</param-value>
</init-param>
<init-param>
<!-- THE "LOGIN" SUB-MODULE -->
<param-name>config/logon</param-name>
<param-value>
/WEB-INF/struts-config-shared.xml, <!-- Using a Shared Struts Configuration File Across Submodules -->
/WEB-INF/struts-config-logon.xml
</param-value>
</init-param>
</servlet>
2. Create each modularized stuts-config.xml:
<!-- struts-config.xml -->
<action-mappings>
<action path="/Listing.do"

</action>
</action-mappings>
<!-- struts-config-admin.xml -->
<action-mappings>
<action path="/Listing.do"

</action>
</action-mappings>
<!-- struts-config-logon.xml -->
<action-mappings>
<action path="/Listing.do"

18

</action>
</action-mappings>
3. Using the html:link tag with the page attribute, add a link to the JSP page that points to the action:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>

</head>
<body>
<html:link page="/Listing.do">Default Listing</html:link>
<html:link page="/admin/Listing.do">Admin Listing</html:link>
<html:link page="/logon/Listing.do">Logon Listing</html:link>
</body>
</html:html>

19

Vous aimerez peut-être aussi