The Action Class

 < Day Day Up > 



The Action class is where the Struts framework ends and your application code begins. As previously mentioned, Action classes provide the glue between the View and Model layers and are responsible for processing specific requests. Action classes are intended to transfer data from the View layer to a specific business process in the Model layer, and then to return data from the business process to the View layer. Business logic should not be embedded in actions, because that violates the principles of MVC.

Each action is mapped to a path in the Struts configuration file. When a request with the specified path is made to the ActionServlet, the action is invoked to process the request. The following snippet illustrates how to configure an action in the Struts configuration file:

<action-mappings>   <action path="/UpdateUser"           type="com.jamesholmes.example.UpdateUserAction"/> </action-mappings>

Which URL is used to access the action depends on how ActionServlet is configured in web.xml. If ActionServlet is configured to use path mapping, the action defined in the preceding example is accessed as http://localhost:8080/MiniHR/do/UpdateUser, assuming a server of localhost running on port 8080 and an application deployed as MiniHR. If extension mapping were used to configure ActionServlet, the URL would be http://localhost:8080/MiniHR/UpdateUser.do.

When an action is called to process a request, its execute( ) method is invoked. The execute( ) method is analogous to the service( ) method in servlets. It handles all processing. Following is an example Action subclass and its execute( ) method:

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class UpdateUserAction extends Action {   public ActionForward execute(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Perform request processing here.   } }

Struts’ Built-In Actions

Struts comes packaged with several built-in utility actions that provide functionality that is useful to many applications. Table 5-2 lists each of the built-in actions and their purpose.

Table 5-2: Struts’ Built-in Utility Actions

Action

Description

org.apache.struts.actions.DispatchAction

Provides a mechanism for modularizing a set of related functions into a single action instead of having to create separate, independent actions for each function.

org.apache.struts.actions.ForwardAction

Provides a mechanism for forwarding to a specified URL.

org.apache.struts.actions.IncludeAction

Provides a mechanism for including the contents of a specified URL.

org.apache.struts.actions.LocaleAction

Provides a mechanism for setting a user's locale and then forwarding to a specified page.

org.apache.struts.actions.LookupDispatchAction

Provides a mechanism for modularizing a set of related functions into a single action instead of having to create separate, independent actions for each function.

org.apache.struts.actions.MappingDispatchAction

Provides a mechanism for modularizing a set of related functions into a single action instead of having to create separate, independent actions for each function.

org.apache.struts.actions.SwitchAction

Provides a mechanism for switching between modules in a modularized Struts application.

The following sections describe each of the built-in actions in detail.

The org.apache.struts.actions.DispatchAction Class

The DispatchAction class provides a mechanism for modularizing a set of related functions into a single action, and thus eliminates 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 AddUserAction class, an UpdateUserAction class, and a RemoveUserAction class, by extending DispatchAction, you can create one UserAction class that has three methods: add( ), update( ), and remove( ). 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.

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. Following is an example UserAction class that extends DispatchAction:

package com.jamesholmes.example; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; public class UserAction extends DispatchAction {   public ActionForward add(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Add user.     …     return new ActionForward("success");   }   public ActionForward update(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Update user.     …     return new ActionForward("success");   }   public ActionForward remove(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Remove user.     …     return new ActionForward("success");   } } 

Notice that this class does not provide an implementation for the execute( ) method the way typical Action classes do. This is because DispatchAction provides to you an implementation of this method that manages delegating to the individual methods. In order for your DispatchAction subclass to work, you must create in the Struts configuration file an action mapping that specifies the name of a request parameter that will be used to select the method that will be called for specific requests. Followingis a sample snippet that illustrates how to do this:

<action-mappings>   <action path="/User"           type="com.jamesholmes.example.UserAction"      parameter="function"/> </action-mappings>

The value specified with the parameter attribute of the action tag will be used as the name of a request parameter that will contain the name of a method to invoke for handling the request. Given the preceding mapping of /User to UserAction, the following URL will invoke the add( ) method (assuming the application was run on your localhost at port 8080 and the application was deployed as /MiniHR/):

http://localhost:8080/MiniHR/User.do?function=add

To invoke the remove( ) method, use the following URL:

http://localhost:8080/MiniHR/User.do?function=remove

The org.apache.struts.actions.ForwardAction Class

The ForwardAction class provides a mechanism for forwarding to a specified URL. As explained earlier, in an MVC Web application, all requests to the application are supposed to flow through the Controller servlet. This ensures that the Controller layer of the application has an opportunity to prepare any resources that may be needed to handle the request (i.e., selecting the correct module and so on). 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. Of course, linking directly to the JSP would be a violation of the MVC principles because all requests are supposed to be routed through the Controller. 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. 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, as shown next:

<action-mappings>   <action path="/menu"           type="org.apache.struts.actions.ForwardAction"      parameter="/menu.jsp/> </action-mappings> 

For each page to which you want to link, you must create an action mapping. Each action mapping uses ForwardAction, but specifies a different path for the action. The parameter attribute specifies the URL that will be forwarded to when the specified path is accessed.

The org.apache.struts.actions.IncludeAction Class

The IncludeAction class provides a mechanism for including the contents of a specified URL. This action 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.

Using IncludeAction is quite easy. Just create action mapping entries in the Struts configuration file:

<action-mappings>   <action path="/menu"           type="org.apache.struts.actions.IncludeAction"      parameter="/menu.jsp/> </action-mappings>

For each page you want to include, you must create an action mapping. Each action mapping uses IncludeAction, but specifies a different path for the action. The parameter attribute specifies the URL that will be included when the specified path is accessed.

The org.apache.struts.actions.LocaleAction Class

The LocaleAction class provides a mechanism for setting a user’s locale and then forwarding to a specified page. This action provides a convenient mechanism for changing a user’s locale. For example, consider a site that is offered in English and Spanish 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. Following is an example of how to configure LocaleAction in the Struts configuration file:

<action-mappings>   <action path="/SwitchLocale"           type="org.apache.struts.actions.LocaleAction"/> </action-mappings> 

Once configured in the Struts configuration file, LocaleAction can be put to use. Simply create a link to the action and specify the locale settings that will be set and a page to forward to. Locale settings are specified with two request parameters: language and country. The page to forward to after setting the locale is specified with the page request parameter. The following URL illustrates how to use the request parameters:

http://localhost:8080/MiniHR/SwitchLocale.do?country=MX&language=es&page=/Menu.do

This example URL sets the country to MX and the language to es. The /Menu.do page will be forwarded to after the new locale has been set.

The org.apache.struts.actions.LookupDispatchAction Class

LookupDispatchAction is a subclass of DispatchAction. The LookupDispatchAction class provides a mechanism for modularizing a set of related functions into a single action, thus 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 AddUserAction class, an UpdateUserAction class, and a RemoveUserAction class, by extending MappingDispatchAction, you can create one UserAction class that has three methods: add( ), update( ), and remove( ).

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. Following is an example UserAction class that extends DispatchAction:

package com.jamesholmes.example; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; public class UserAction extends LookupDispatchAction {   protected Map getKeyMethodMap()   {     HashMap map = new HashMap();     map.put("button.add", "add");     map.put("button.update", "update");     map.put("button.remove", "remove");     return map;   }   public ActionForward add(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Add user.     …     return new ActionForward("success");   }   public ActionForward update(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Update user.     …     return new ActionForward("success");   }   public ActionForward remove(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Remove user.     …     return new ActionForward("success");   } }

Notice that this class does not provide an implementation for the execute( ) method as other Action classes do. This is because DispatchAction provides to you an implementation of this method that manages delegating to the individual methods. Notice also the implementation of the getKeyMethodMap( ) method. This method 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. The keys’ values in the bundle file are used to match against the value of the incoming request parameter specified by the parameter attribute of the action tag in the Struts configuration file.

In order for your LookupDispatchAction subclass to work, you must create in the Struts configuration file an action mapping that specifies the name of a request parameter that will be used to select the method that will be called for a specific request. Following is a sample snippet that illustrates how to do this:

<action-mappings>   <action path="/User"           type="com.jamesholmes.example.UserAction"      parameter="function"/> </action-mappings>

The value specified with the parameter attribute of the action tag will be used as the name of a request parameter that will contain the value of a key in the Struts resource bundle shown here:

button.add=Add User button.update=Update User button.remove=Remove User

LookupDispatchAction will use the value of the incoming request parameter to perform a reverse lookup for a key in the resource bundle. The matching key is then mapped to the appropriate method to execute based on the key-to-method mapping specified by the getKeyMethodMap( ) method.

Given the preceding mapping of /User to UserAction, the following URL will invoke the add( ) method (assuming the application was run on your localhost at port 8080 and the application was deployed as /MiniHR/):

http://localhost:8080/MiniHR/User.do?function=Add%20User

To invoke the remove( ) method, use the following URL:

http://localhost:8080/MiniHR/User.do?function=Remove%20User

The org.apache.struts.actions.MappingDispatchAction Class

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 AddUserAction class, an Update UserAction class, and a RemoveUserAction class, by extending MappingDispatch Action, you can create one UserAction class that has three methods: add( ), update( ), and remove( ). 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. Following is an example UserAction class that extends MappingDispatchAction:

package com.jamesholmes.example; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.MappingDispatchAction; public class UserAction extends MappingDispatchAction {   public ActionForward add(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Add user.     …     return new ActionForward("success");   }   public ActionForward update(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Update user.     …     return new ActionForward("success");   }   public ActionForward remove(ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)     throws Exception   {     // Remove user.     …     return new ActionForward("success");   } }

Notice that this class does not provide an implementation for the execute( ) method as other Action classes do. This is because MappingDispatchAction provides to you an implementation of this method that manages delegating to the individual function methods.

In order for your MappingDispatchAction subclass to work, you must create in the Struts configuration file action mappings that specify the method that will be called for specific requests. Following is a sample snippet that illustrates how to do this:

<action-mappings>   <action path="/AddUser"           type="com.jamesholmes.example.UserAction"      parameter="add"/>   <action path="/UpdateUser"           type="com.jamesholmes.example.UserAction"      parameter="update"/>   <action path="/RemoveUser"           type="com.jamesholmes.example.UserAction"      parameter="remove"/> </action-mappings> 

Notice that each action mapping uses the UserAction class, but specifies a different path for the action. Each of the unique paths will be processed by the same action, but a different method will be called based on the value specified with the parameter attribute. The value specified with the parameter attribute must match the name of a method in your MappingDispatchAction subclass.

The org.apache.struts.actions.SwitchAction Class

The SwitchAction class provides a mechanism for switching between modules in a modularized Struts application. As you’ll see in Chapter 9, Struts enables you to modularize your Struts application. Each module has its own set of configuration data as well as its own request processor. 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.

Note 

Detailed information on using Struts’ modules feature is found in Chapter 9.

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. Following is an example of how to configure SwitchAction in the Struts configuration file:

<action-mappings>   <action path="/SwitchModule"           type="org.apache.struts.actions.SwitchAction"/> </action-mappings>

Once configured in the Struts configuration file, SwitchAction can be put to use. Simply create a link to the action and specify the module to switch to and a page to forward to afterward. The module to switch to is specified with the prefix parameter and the page to forward to afterward is specified with the page parameter. The following URL illustrates how to use the request parameters:

http://localhost:8080/MiniHR/SwitchModule.do?prefix=/Corporate&page=/Menu.do

This example URL switches to the /Corporate module, and the /Menu.do page will be forwarded to after the module has been switched.



 < Day Day Up > 



Struts. The Complete Reference
Struts: The Complete Reference, 2nd Edition
ISBN: 0072263865
EAN: 2147483647
Year: 2003
Pages: 134
Authors: James Holmes

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net