Struts2 's Action (iv)

Source: Internet
Author: User

Implement action

Action is at the heart of the Struts2 application, where a large number of action classes are required and the action is configured in Struts.xml. The action contains the processing logic for the user request, and the action class is also known as the Business control logic.

The STRUTS2 uses a low-intrusive design that does not require the action class to inherit any of the struts base classes or implement any struts interfaces. Struts2 's action class is a common Pojo class (usually with a non-parametric method) and thus has good code reusability.

Struts2 usually encapsulates HTTP parameters directly using action, so the action class should also contain the instance variables corresponding to the request parameters, and provide the appropriate setter and getter methods for those instance variables.

For example, a user request contains ProductName and productdesc two request parameters, the action class should provide ProductName and Productdesc two instance variables to encapsulate the user request parameters, and provide the corresponding setter and getter method for ProductName and Productdesc. Here is the code snippet for the action class that handles the request:

//The action class that processes the user request, just a pojo, without inheriting any base class, or implementing any interface Public classProduct {//Provide instance variables to encapsulate HTTP request Parameters    PrivateInteger productId;PrivateString ProductName;PrivateString Productdesc;Private DoubleProductprice;//appropriate setter and Getter methods     PublicIntegerGetProductID() {returnProductId; } Public void Setproductid(Integer productId) { This. productId = ProductId; } PublicStringGetproductname() {returnProductName; } Public void Setproductname(String productName) { This. productName = ProductName; } PublicStringGetproductdesc() {returnProductdesc; } Public void Setproductdesc(String Productdesc) { This. Productdesc = Productdesc; } Public Double GetProductPrice() {returnProductprice; } Public void Setproductprice(DoubleProductprice) { This. Productprice = Productprice; }the//action class handles user requests by default: The Execute method     PublicStringExecute(){       ...//Return processing result string       returnResultStr; }


Although the action needs to handle requests that contain HTTP request parameters such as ProductName and Productdesc, the action class may not contain their corresponding instance variables. Because the system uses the corresponding setter and getter methods to process the request parameters, instead of handling the request parameters through the instance variables. That is, whether the action class contains the corresponding instance variable is not important, it is important to include the void Setproductname (string productName) and the string Getproductname () method.

Instance variables in the action class can be used not only to encapsulate request parameters, but also to encapsulate processing results. If you want the server prompt to "register successfully" or other information to be output on the next page, you can add a tip instance variable to the action class and provide it with a corresponding setter and getter method,

//Package Tip instance variable for service tip  private  String tip; //tip corresponding setter and getter method  public  String gettip  () {return  tip; Pubic void  settip (String tip) {this . tip = tip;} //action contains the registration control logic  public    String register  () throws  exception{   Actioncontext.getcontext (). GetSession (). Put ( "user" , GetUserName ()); Settip ( "welcome you!"  + getusername () +  "you have registered successfully!"   "); return  SUCCESS;}  

You can use the Struts2 label on the next page to output the value of the instance variable. The output Tip instance variable in the Load JSP page is worth the code snippet as follows:

value="tip"/>


The system does not strictly differentiate which instance variable in the action is used to encapsulate the request parameter and which instance variable is used to encapsulate the processing result. If the user's HTTP request contains a request parameter named tip, the system calls the void Settip (String tip) method, in which case the request parameter named tip can be passed to the action instance, and if the action class does not contain a corresponding method, The request parameter named tip will fail to pass in the action.

When you output an instance variable value for an action in a JSP page, you do not differentiate whether the instance variable is used to encapsulate the parameter or the result. Therefore, the STRUTS2 tag can output both the action's processing result and the HTTP request parameter value.

Action interface and action base class

To standardize the action class development, STRUTS2 provides an action interface that defines the specifications that the Struts2 action class should implement for the interface:

 Public  interface Action {    //Define some result strings contained in the action interface     Public Static FinalString SUCCESS ="Success"; Public Static FinalString NONE ="None"; Public Static FinalString ERROR ="Error"; Public Static FinalString INPUT ="Input"; Public Static FinalString LOGIN ="Login";//Define the Execute method that handles user requests     PublicStringExecute()throwsException;}


An Execute method is defined in the action interface, which defines that the action class should contain an Execute method that returns a string. The interface also defines 5 string constants that are used to unify the return value of the Execute method. The General action class handles user requests after someone likes to return the welcome string, and someone likes to return success character channeling ... This is not conducive to a unified association, so the action interface defines these 5 string constants: ERROR,
INPUT, login, and success, respectively, represent specific meanings. However, if developers want to use their own strings as logical view names, they can still be allowed, but this does not take advantage of post-maintenance.

STRUTS2 also provides an implementation class Actionsupport for the action interface, which contains related methods, etc. see figure



Acitonsupport is a default action implementation class that has many default methods, including methods for obtaining internationalized information, methods for validating data, and the default method of handling user requests. It is the default action handler class for STRUTS2, which greatly simplifies the development of the action if the developer's action class inherits the Actionsupport class.

Action Access servlet API

Struts2 's action is not coupled to any servlet API, making it easy to test the action. However, Web application controllers often require access to the Servlet API, such as tracking the HttpSession state, and the servlet APIs that are typically accessed by Web applications are HttpServletRequest, HttpSession, ServletContext, these three interfaces represent the request, session, and application in the JSP's built-in objects, respectively.

How to access the Servlet API decoupling:

To avoid coupling with the Servlet API and to facilitate unit testing of the Action, STRUTS2 has encapsulated HttpServletRequest, HttpSession and ServletContext, and constructed 3 Map objects Instead of these 3 objects, you can use HttpServletRequest, httpservletsession, servletcontext the corresponding Map object in Action to save and read the data.

The STRUTS2 providesActioncontext class, Actioncontext is the context object that the action executes, and all the objects needed to execute the action are saved in Actioncontext, including parameters, request, session, application, and so on.

Gets the map object for the HttpSession:
Public Map getsession ()
Gets the map object for the ServletContext:
Public Map getapplication ()
Gets the map object that corresponds to the request parameter:
Public Map getparameters ()
Gets the map object for the HttpServletRequest:
public object get (Object key): The Actioncontext class does not provide a method like Getrequest () to get httpservletrequest corresponding Map object. To get the map object for HttpServletRequest, you can pass the request parameter implementation for the Get () method.

The complete method is as follows:



access mode coupled to the Servlet:

Accessing the Servlet API with Actioncontext is not directly an instance of the Servlet API. The following interfaces are provided for direct access to servlet api,struts2 in action:

|>servletcontextaware: The action that implements the interface can directly access the ServletContext instance of the Web App.
|>servletrequestaware: The action that implements the interface can directly access the Httpservletrquest instance requested by the user.
|>servletresponseawre: The action that implements the interface can directly access the HttpServletResponse instance of the server response.

In addition, STRUTS2 provides a Servletactioncontext tool class that accesses the servlet API directly,



The Servletactioncontext class provides access to the SERLEVT API in action and avoids the need for the action class to implement the Xxxaware interface, but the action is still directly coupled to the servlet API, which requires Servlet containers, which do not facilitate unit testing of the Action, are not conducive to high-level decoupling.

Dynamic method Invocation of action

This write action related, should also involve the basic configuration of the action, but the previous chapter on the development process, the basic introduction, here no longer talk about, directly see action dynamic method call.

Many times an action is required to contain multiple control processing logic. For example, for the same form, users may want to submit the same form system by logging in or registering two different submit buttons to handle user requests using different methods of action, which requires that the same action contain multiple control processing logic.

The login button processes the request using the login logic, and the Register button processes the request using the registration logic. Requests can be processed using the DMI (dynamic Method Invocaton), which is called dynamically. The action of a FORM element in a dynamic method call is not directly equal to the name of an action, but instead specifies the form's Action property as follows.

fun(){<!--action属性为actionName!methodName的形式-->target.action="action!methodName";}


If we can write the code for the "Register" button on the JSP page:

<!--注册按钮没有任何动作,但单击该按钮时触发regist函数--><input type"submit" value="注册" onClick="regist();">


regist function JavaScript code:

function regist(){   //获取页面的第一个表单   targetForm = document.forms[0];   "login!regist";}


The last line of code means that the form is submitted to the login action's Regist method for processing. The code for the Loginregistaction class is as follows:

 Public  class loginregistaction extends actionsupport{   //Encapsulates two member variables for user request parameters   PrivateString username;PrivateString password;//Wrap Tip member variables for processing results   PrivateString tip;//Omit setter and Getter methods...//action contains the registration control logic    PublicStringRegister()throwsexception{Actioncontext.getcontext (). GetSession (). Put ("User", GetUserName ()); Settip ("Welcome to you!"+ getusername () +"You have registered successfully!" ");returnSUCCESS; }//action control logic that is included by default    PublicStringExecute()throwsexception{if(GetUserName (). Equals ("Jujiu") &&getpassword (). Equals ("1357afy") {Actioncontext.getcontext (). GetSession (). Put ("User", GetUserName ()); Settip ("Welcome to you!"+ getusername () +"You have registered successfully!" ");returnSUCCESS; }                 }}

By default, the Execute method is called, and when the user clicks the login, the system submits the form to the Loginactionaction default method, and when the user clicks the Register button, the form's Action is modified to: Login!regist, the system is submitted to the login action (ie, loginregistaction) is handled by the Regist method. This way you can make an action contain multiple logical processes and submit different methods to the action by specifying different action properties for the form element.

Using dynamic method Invocation, where the methods such as the declaration of the Regist method and the system default execute method are different except for the method name, the other such as the formal parameter list and the return value type should be identical.

You need to set STRUTS2 to run dynamic method calls before using dynamic method calls, that is, set the value of the Struts.enable.DynamicMethodInvocation constant to True. There are security flaws in the DMI approach. Often not recommended.

The method property specifies the methods and wildcard characters used

You can use the method property in to configure an action class as more than one logical action to have the action invoke the specified method.

<struts>  < package name="HelloWorld" extends= "struts-default">     <action name="Login" class="Com.afy.LoginRegist">        <result name="Details">/web-inf/pages/welcome.jsp</result>     </Action>    <action name="Regist" class="Com.afy.LoginRegist " method ="Regist">      <result name="Details">/web-inf/pages/welcome.jsp</result>     </Action> </Package ></struts>

This defines the login and regist two logical actions, the processing classes are loginregist, the processing logic is specified by the method methods, and the processing logic for login's action is the default Execute method, The regist action corresponding to the processing logic is the specified Regist method. The corresponding JavaScript code should read:

function regist(){   //获取页面的第一个表单   targetForm = document.forms[0];   "regist";}

We have found that many of the definitions in the < action.../> are the same, resulting in redundancy, and you can consider using wildcard methods at this time. In configuration < Action.../>, using a pattern string when specifying the Name property ("*" for one or more arbitrary characters), you can use the expression {N} in the class, method property, and < result.../> child elements Replaces the substring of the preceding nth asterisk.

<struts>  < package name="HelloWorld" extends= "struts-default">     <action name="*action" class="Com.afy.LoginRegist " Method="{1}">        <result name="Details">/web-inf/pages/welcome.jsp</result>     </Action> </Package ></struts>

Struts2 's Action (iv)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.