Struts2 Action, struts2action

Source: Internet
Author: User

Struts2 Action, struts2action

1. namespace: the space where the package is located. The action path of the access package is http: // localhost: 8080/project name/namespace/index. action.
Namespace can also be left empty,
Assume that the access path is http: // localhost: 8080/aaa/bbb/index. action,
No package space for aaa and bbb is found in struts. xml.
As long as an index. action is found and the corresponding package is not found, it is called a package with the namespace being empty.
Therefore, a package with an empty namespace contains actions that cannot be processed by other packages.

    <package name="front" namespace="/front" extends="struts-default">        <action name="index">            <result name="success">/hello.jsp</result>        </action>            </package>    <package name="front2" extends="struts-default">        <action name="index">            <result name="success">/hello.jsp</result>        </action>            </package>

 




2. action:

  <package name="front3" extends="struts-default">        <action name="index" class="xxx.xxx.xx.FirstAction">            <result name="success">/hello.jsp</result>        </action>            </package>

Three ways to implement action
A.

Public class FirstAction {public String execute () {return "success ";}}
All methods must be written by yourself. Poor syntax Control

B.

Public class FirstAction implements Action {public String execute () {return "success" ;}} there is only one execute () abstract method in the Action Interface

C.

Public class FirstAction extends ActionSupport {public String execute () throws Exception {return "success" ;}} use the third type, because ActionSupport has encapsulated some convenient methods that can be directly called in the subclass.

 



3. dynamic method call (DMI)
The url for calling the add () method in UserAction is:
Http: // localhost: 8080/project name/namespace/user! Add. action

<package name="user" namespace="/user" extends="struts-default" >        <action name="user" class="com.zr.struts.user.action.UserAction">            <result>/user_add_success.jsp</result>        </action></package>

 


4. wildcard configuration: the configuration quantity can be minimized.
The url for calling the add () method in UserAction is:
Http: // localhost: 8080/project name/namespace/useradd. action

 <package name="user" namespace="/user" extends="struts-default" >        <action name="user*" class="com.zr.struts.user.action.UserAction" method="{1}">            <result>/user_{1}_success.jsp</result>        </action> </package>

 



The url for calling the add () method in UserAction is:
Http: // localhost: 8080/project name/namespace/User_add.action)
It is equivalent to calling the add () method in UserAction to return to the User_add_success.jsp page.

 <package name="User" namespace="/user" extends="struts-default" >        <action name="*_*" class="com.zr.struts.user.action.{1}Action" method="{2}">            <result>/{1}_{2}_success.jsp</result>        </action> </package>

 


5. The property of action to accept parameters

 <package name="user" namespace="/user" extends="struts-default" >        <action name="user" class="com.zr.struts.user.action.UserAction">            <result>/user_add_success.jsp</result>        </action> </package>

A. Method 1:
Http: // localhost: 8080/project name/namespace/user! Add? Name = xxx & age = XXX. action
Define two attributes in UserAction:
Private Sring name; private int age; provides the get/set method.
In this way, the get/set method will be automatically called to access this Action to receive the two parameters name and age.
B. Method 2:
Http: // localhost: 8080/project name/namespace/user! Add? User. name = xxx & user. age = XXX. action
Use the Model to accept parameters
Define a property in UserAction: private User user;
Modle User has two attributes: private Sring name; private int age; and provides the get/set method.
The getUser/setUser method is provided in UserAction.
C. Method 3:
Http: // localhost: 8080/project name/namespace/user! Add? Name = xxx & age = XXX. action
UserAction implements a ModelDriver <T> Interface

Public class UserAction extends ActionSupport implements ModelDriver <User> {private User user User; @ Override public user getModel () {return User ;}}
Struts2 will automatically call getModle () and pass the parameter name and age to the user;


6. encoding of struts2:

You only need to configure <constant name = "struts. i18n. encoding" value = "UTF-8"/> In struts. xml

 

No configuration is required, because its default value is UTF-8.

7. SimpleDateValidates
Http: // localhost: 8080/project name/namespace/user! Add? Name = xxx. action

 public class UserAction extends ActionSupport{        pirvate String name;        public String add(){           if(name == xxx){            this.addFieldError("name","name is error")                    }
       return "error"; } public String getName(){return name;} public void setName(String name){this.name = name;} }

 


The error message is displayed in the jsp file:
1. Use struts2 labels:
<S: fielderror fieldName = "name"/> the error message displayed in this method automatically adds the CSS format (<li>)

2. Retrieve error information from value Stack (both errors and FieldErrors can be used)
<S: property value = "errors. name"/> (errors: {name = [name is error]})
(Errors is an attribute in the Value Stack and is a Map <key, value>, where value is an array)
<S: property> tags are used to obtain attributes in Value Stack and Stack Context.
<S: debug> tag (a link named debug is displayed on the page). You can view the attributes in Value Stack.

8. access the web element of struts2 (obtain the request, session, and application of the Map type)
Reference of the actual type HttpServletRequest, HttpSession, and ServletContext)
Method 1: (dependent on web containers)

   public class LoginAction extends ActionSupport {            private Map<String, Object> request;            private Map<String, Object> session;            private Map<String, Object> application;            public LoginAction(){                request = (Map)ActionContext.getContext().get("request");                session = ActionContext.getContext().getSession();                application = ActionContext.getContext().getApplication();            }                        public String execute(){                request.put("a", "aa");                session.put("b", "bb");                application.put("c", "cc");                return "success";            }   }

 



You can use the following methods to retrieve the jsp page:
(Stored in the Stack Context. You must add # to obtain the information. For details, use the <s: debug> label)
Method 1:

        <s:property value="#request.a" />            <s:property value="#session.b" />            <s:property value="#application.c" />

 


Method 2: (it indicates that struts must establish a certain relationship between the three Map types and the three real types, and copy the values in the Map)

         <%=request.getAttribute("a") %>            <%=session.getAttribute("b") %>            <%=application.getAttribute("c") %>

 


Method 3: (attr automatically searches for the values of attribute names a, B, and c, provided that the attribute names cannot be repeated)

  <s:property value="#attr.a" />  <s:property value="#attr.b" />   <s:property value="#attr.c" />

 



Method 2: (most commonly used) Implement the RequestAware, SessionAware, and ApplicationAware Interfaces
(Dependency on web containers reflects IOC inverse of control inversion)
Method 1: the three maps are initialized by the user and are dependent on external injection (DI dependency injection)
Process: struts2 receives a request, first creates a corresponding Action, and then determines whether the Action has been implemented.
If the above three interfaces are implemented, struts2 calls the corresponding set method and uses the three Map
Initialize three maps of the Action; (that is, struts2 initializes these three maps, which fully reflects the control inversion)

Supplement: The request rarely retrieves it, because the member variables in the Action (stored in the Stack Value) play the role of the request.
Application is rarely used. If global content is defined, it is generally stored in the database or defined as a class.

  public class UserAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware {            private Map<String, Object> request;            private Map<String, Object> session;            private Map<String, Object> application;                        public String execute(){                request.put("a", "aa");                session.put("b", "bb");                application.put("c", "cc");                return "success";            }            @Override            public void setRequest(Map<String, Object> arg0) {                this.request = request;            }            @Override            public void setApplication(Map<String, Object> application) {                this.application = application;            }            @Override            public void setSession(Map<String, Object> session) {                this.session = session;            }  }    

 


Method 3: Get the reference of the actual type HttpServletRequest, HttpSession, and ServletContext

   public class UserAction extends ActionSupport {            private HttpServletRequest request;            private HttpSession session;            private ServletContext application;                        public UserAction(){                request = ServletActionContext.getRequest();                session = request.getSession();                application = session.getServletContext();            }       }

 



Method 4: implement the ServletRequestAware interface (dependency injection, IOC)

 public class UserAction extends ActionSupport implements ServletRequestAware {            private HttpServletRequest request;            private HttpSession session;            private ServletContext application;            @Override            public void setServletRequest(HttpServletRequest request) {                this.request = request;                this.session = request.getSession();                this.application = session.getServletContext();                    }    }

 


8. The inclusion of struts2 modules <include file = "xxx. xml"/> is of great significance.
9. Default Action of struts2: if the requested Action does not exist or the requested Action is not specified, it will automatically jump to the default Action.

<package name="user" namespace="/user" extends="struts-default" >        <default-action-ref name="default"></default-action-ref>        <action name="default" >            <result>/default.jsp</result>        </action></package>

 

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.