Implementation and configuration of STRUTS2 note--2.action

Source: Internet
Author: User

Implement action

In Struts2, action is responsible for handling user requests, so it is the controller for the entire application and the core of the application as a whole. For developers, they need to provide a large number of action classes. Struts2 is less immersed than struts1 because its action does not inherit any parent class or interface, just a normal pojo (but should include an Execute method without arguments). Struts2 usually use the action directly to encapsulate the HTTP request parameters (which can be understood as parameters in the form, such as Username,password, etc.), so these properties should be provided in the corresponding action class. In addition, the instance variables inside the action can encapsulate the processing results. The property of the S tag is used on the next page to output the results (you can also use more complex tags to output complex instance variables). in fact, the system does not distinguish which encapsulation request, which package processing results.

Action interface and Actionsupport base class

Although the action class does not need to inherit any classes, it does not implement any interfaces, but in order to develop more specification, STRUTS2 provides an action interface. This interface defines the string constants for five logical views, and an Execute method. In addition, STRUTS2 provides a Actionsupport implementation class for the action interface. Many methods are defined in this class, which is commonly used by execute, which returns success. So if we inherit the Actionsupport class directly, it will greatly simplify development.

Action Access servlet API

The action in STRUTS2 does not have any coupling with the servlet, so we can test the action individually. But sometimes we do need to access the Servlet API. The so-called access API, plainly, is to operate request,session,application. Three of them are built-in objects for JSPs, and Servlets have three interfaces representing three of them. So accessing the servlet API is the operation of these three built-in objects. in STRUTS2 we can operate through the Actioncontext class. use actioncontext.getcontext () to get the Actioncontext instance first, and then use the Getapplication, GetParameters or GetSession Get Application object, request object, or Session object. These objects are then manipulated using the Get or Put method (corresponding to the GetAttribute or SetAttribute method in the JSP or servlet).

First, an AC instance is obtained, and the servlet apiactioncontext Ac=actioncontext.getcontext () can be manipulated by its method, and the//get method can return the parameter of the corresponding name in the request. AC direct call put and get operations are all requeststring password1= (String) ac.get ("password"), Ac.put ("NewPassword", "123");// Both the application and the session need to get their corresponding map object before they can be manipulated. String password2= (String) ac.getapplication (). Get ("password"); Ac.getapplication (). Put ("NewPassword", "123"); String password3= (String) ac.getsession (). Get ("password"); Ac.getsession (). Put ("NewPassword", "123");

ACTIon Direct access to the servlet API

For more direct access, STRUTS2 provides several interfaces: Servletcontextaware, Servletrequestaware, and Servletresponseaware. The action that implements these interfaces directly accesses the corresponding API. For example, if you want to get the request, simply declare a request variable in the action, then implement the corresponding interface and assign the parameters of the interface to the request variable in the action.

public class Myaction extends Actionsupport implements Servletcontextaware{private String password;private HttpServletResponse response;private httpservletrequest request;private servletcontext context; @Overridepublic void Setservletcontext (ServletContext arg0) {//TODO auto-generated method stubthis.context=arg0;}

accessing the servlet API using Servletactioncontext

Servletactioncontext is a tool class with some static methods, such as Getpagecontext,getrequest,getresponse,getservletcontext. This access method is convenient, but because it is coupled with the servlet, it is not conducive to high-level decoupling.

Private HttpServletResponse response;private httpservletrequest request;private servletcontext context;private PageContext PageContext; @Overridepublic String execute () throws Exception {//These four static methods can be used directly. response= Servletactioncontext.getresponse (); Request=servletactioncontext.getrequest (); context= Servletactioncontext.getservletcontext ();p agecontext=servletactioncontext.getpagecontext (); return Super.execute ();}


Configure Action

After implementing the action class, we want to tell the framework which request corresponds to which action, so it needs to be configured in Struts.xml.


Packages and Namespaces

STRUTS2 uses packages to manage Action,result and interceptor. Each package element can only be configured with one packet. The Name property of the package is a unique indicator that references it. In addition, packages can inherit, inheriting all configurations from multiple parent packages (typically we define packages that inherit Struts-default). If you are inheriting other packages, the extends property must be the property of another package. There is also an abstract package that is used only for inheritance, identified by an abstract.

Since it may be necessary to have more than one name action in a Web application, the concept of namespaces is introduced in order to omit the same action name and also to solve the problem of duplicate action in large projects. Actions in the same namespace cannot have duplicate names, and different namespaces can have the same name. The package is used to manage the action, and namespace is used to access the action-sensitive namespace, which is a property of the packet. namespace must start with/.

STRUTS2 does not support setting a namespace for a separate action, but instead specifies the namespace property through the package to specify a common namespace for all actions under the package. If you do not specify the namespace attribute when you configure the package, all the actions under the packet are in the default package space, that is, if nothing is written, the equivalent of namespace is "". When a package specifies a namespace, all action-handling URLs under the package should be the namespace +action name. Because the Struts.xml file is loaded from top to bottom, the parent package should precede the child package.

<package name= "cmaction" extends= "Struts-default" namespace= "/loginrelated" ><action name= "Rightuser" class = "Com.cm.example" method= "execute" ><result name= "Success" >/web-inf/aaa.jsp </result><result name = "Error" >/WEB-INF/error.jsp</result></action></package>

It is important to note that the view resource of result corresponds to/begins with.


Dynamic method Invocation of action

If you want two buttons in a form to use different action handles (they are all submit buttons), you need to use a script to change the Action property in the form when the button is onclick.

The Action property is changed by using the onclick as follows:

<script type= "Text/javascript" > Function Lalala () {targetform=document.forms[0];      Targetform.action= "Loginrelated/rightuser";}  </script> <form action= "Loginrelated/rightadsgadsgadguseearr" method= "POST" > <input type= "Submit" Value= "Click Me" onclick= "Lalala ()"/> </form>

wildcards: using wildcards, you can simplify operations and greatly reduce the number of action configurations. For a processing class, you only need to configure it once. The wording is as follows:

<action name= "*lalala" class= "Com.cm.example" method= "{1}" ><result name= "Success" >/web-inf/aaa.jsp < /result></action>


Default handling class for action and action

<package name= "cmaction"  extends= "Struts-default"   Namespace= "/loginrelated" >    <default-action-ref name= "DEFAULT1" ></ default-action-ref>    <default-class-ref class= "Com.cm.defaultaction" ></ Default-class-ref><action name= "*lalala"  class= "Com.cm.example"  method= "{1}" >< Result name= "Success" >/web-inf/aaa.jsp </result></action><action name= " Default1 " class=" Com.cm.defaultaction "><result>/web-inf/defaultpage.jsp</result></ Action></package> 


NOTE: If you configure DefaultAction in the default namespace, it will be able to act as the default action for all requests. Because the package inherits Struts-default, the default action

This article from "Fingertip Light Fly" blog, declined reprint!

Implementation and configuration of STRUTS2 note--2.action

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.