STRUTS2 Basic Learning (ii)-action

Source: Internet
Author: User

First, Actionsupport

To make the user-developed action class more canonical, STRUTS2 provides an action interface that defines the specifications that the Struts2 action class should implement. The following is the code for the Standard action interface:

Public interface Action {public    static final String SUCCESS = "SUCCESS";    public static final String none = "None";    public static final String error = "error";    public static final String input = "input";    public static final String login = "Login";    Public String Execute () throws Exception;}

The action interface above only defines an execute () method, which specifies that the action class should contain an execute () method that returns a string, and that the interface defines 5 string constants, which is the function of uniform execute () The return value of the method.

STRUTS2 also provides an implementation class for the action interface: Actionsupport.

Actionsupport is a default action implementation class that already provides a number of default methods, including Form field validation, error message setup, and access to internationalized information , in fact, Actionsupport is the default action class for STRUTS2, and if you let the developer's action class inherit the Actionsupport class, it will greatly simplify the development of the action.

Second, configure the action with a wildcard character

(1) When configuring the <action> element, allows the use of a pattern string (with "*" for one or more arbitrary characters) when specifying the Name property.

(2) In the class, method attribute and <result> sub-element, the {n} form represents the preceding n * matching substring.

The *_* represents a match of two strings.

The {1} match useraction is used to execute class.

The {2} match login is used to specify method execution methods and results pages.

Package Declaration

Can be rewritten as:

Iii. Invocation of dynamic methods

(1) Dynamically specify which method to invoke the action by using the URL without configuring the <action> methods property.

(2) Pass ! The method name specifies which method to call the action.

<action name= "cus" class= "com.kiwi.action.CusAction" ><result name= "Success" >/success.jsp</result ></action>

Access path:

Struts2 is not accessible by default in this way, you must configure a constant.

<!--allow dynamic access to--><constant name= "Struts.enable.DynamicMethodInvocation" value= "true"/>

Four, the default action

If the user enters a non-existent action, the default is an error, and we can configure a default action.

<!--user-accessed action if it does not exist, the default action--><default-action-ref name= "DefaultAction" is accessed ></ Default-action-ref><action name= "DefaultAction" ><result>/success.jsp</result></action >
For example:

V. Accessing Web Resources

In action, if you want to access the Servlet native APIs such as HttpSession, HttpServletRequest, HttpServletResponse, we can do this in two different ways.

(1) Access in a way that is decoupled from the Servlet API

A: by Actioncontext

B: Implement Applicationaware, Sessionaware, Requestaware interface

(2) Access in a way that is coupled to the Servlet API

A: by Servletactioncontext

B: Implement Servletapplicationaware, Servletsessionaware, Servletrequestaware interface

1. 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 object to replace these 3 objects, the map object corresponding to 3 objects can be used to save and read data directly in the action.

(1) Access to Web resources through Actioncontext

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.

Public Map GetSession (): gets the map corresponding to the httpsession.

Public Map Getapplication (): gets the map corresponding to the ServletContext.

Public Map GetParameters (): Gets the map that corresponds to the object get request parameter.

Public object Get (Object key): A method similar to Getrequest () is not provided in the Actioncontext class to obtain the map object for the request. To get the map object for HttpServletRequest, you can pass the request parameter implementation for the Get () method.

index.jsp

<a href= "${pagecontext.request.contextpath}/testservlet.action?name=tom" >struts2 Getting Started </a>

Struts.xml

<action name= "Testservlet" class= "com.kiwi.action.ServletTestAction" ><result name= "Success" >/ Result.jsp</result></action>

result.jsp

  <body>        Application: ${applicationscope.applicationkey}<br>     session: ${ sessionscope.sessionkey}<br>     Request: ${requestscope.requestkey}<br>     Name: ${parameters.name [0]} <br>       </body>

Servlettestaction.java

public class Servlettestaction extends actionsupport{@Overridepublic String execute () throws EXCEPTION{//1. Gets the Actioncontext object, which is the context object of the action Actioncontext Actioncontext = Actioncontext.getcontext ();//2. Get application corresponding map, and add an attribute map<string,object> Applicationmap = actioncontext.getapplication (); Applicationmap.put (" Applicationkey "," This is the value of application ");//3. Get the session map and add a property map<string,object> Sessionmap =     Actioncontext.getsession (); Sessionmap.put ("SessionKey", "This is the value of the session");/* * 4. Get the request map and add a property * Note: * The Getrequest () method is not available in Actioncontext to get the map * corresponding to the request to call the Get () method and pass in the "request" character to get the */map<string,object> Requestnmap = (map<string,object>) actioncontext.get ("Request"), Requestnmap.put ("Requestkey", "This is the value of request") ;/* * 5. Gets the request parameter corresponding to the MAP and gets the specified parameter value * NOTE: * 1. Key: The name value of the request parameter: an array of strings corresponding to the request parameters * 2.paramters This Map can only read or write */Map<string,ob ject> Parametersmap = Actioncontext.getparameters (); String[] names = (string[]) parametersmap.get ("name"); System.out.println("Name:" + names[0]); Tomreturn SUCCESS;}}

Results:

(2) Access to Web resources by implementing aware
The action class allows the STRUTS2 framework to inject parameters, request, session, and application corresponding map objects at runtime to the action instance by implementing some specific interfaces.

public class Servlettest2action extends Actionsupport implements Applicationaware,sessionaware,requestaware, Parameteraware{private map<string,object> application;private map<string,object> session;private Map <String,Object> request;private map<string,string[]> parameters; @Overridepublic String execute () throws EXCEPTION{//1. Add an attribute application.put ("Applicationkey", "Application Value---Interface implementation") to application;//2. Add an attribute session.put ("SessionKey", "Session Value---Interface implementation") to the session;//3. Add a property request.put to the request ("Requestkey", " Request Value---interface implementation ");//4. Reads the specified value from parameters string[] names = Parameters.get (" name "); System.out.println (Names[0]); Tomreturn SUCCESS;} @Overridepublic void Setapplication (map<string,object> application) {this.application = Application;} @Overridepublic void Setsession (map<string,object> session) {this.session = session;} @Overridepublic void Setrequest (map<string,object> request) {this.request = Request;} @Overridepublic void Setparameters (Map<string,strinG[]> parameters) {this.parameters = parameters;}} 

Results:

Recommendation: If there is more than one action method in an action class, and multiple methods require a map or parameters of the domain object, it is recommended to use a method that implements the interface.

2. Accessing Web resources in a way that is coupled with a servlet

(1) Access to Web resources through Servletactioncontext

getsession (): Gets the HttpSession object directly.

getrequest (): Gets the HttpServletRequest object directly.

Getservletcontext (): get Httpservletcontext object directly

(2) Access to Web resources by implementing aware

Implement the Servletrequestaware, Servletcontextaware interface way.

STRUTS2 Basic Learning (ii)-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.