The third day of Struts2 learning-saving login information and data verification and struts2 Verification

Source: Internet
Author: User

The third day of Struts2 learning-saving login information and data verification and struts2 Verification

In JSP, the server stores data in the following scopes: request, session, and application. The Servlet APIs are HttpServletRquerst, HttpSession, and ServletContext. Similarly, the Struts2 controller also needs to access these scopes.

Struts2 provides an ActionContext class called Action context or Action environment. Action can access the most common ServletAPI through this class.

ServletAPI provides multiple access methods:

1.Servlet API decoupling access method, using ActionContext to access ServletAPI

Common methods include:

GetContext (): static method to obtain the current ActionContext instance.

GetSession (): returns a Map object that simulates the session scope.

GetApplication (): returns a Map object that simulates the application scope.

Get (String key): You can pass in the "request" parameter to this method to return an Object that simulates the request scope.

GetParamenters (); returns a Map object that stores the parameters uploaded by the browser. The Code is as follows:

1 // obtain the context 2 ActionContext context = ActionContext. getContext (); 3 // associate the data in the request range with 4 Map requestMap = (Map) context. get ("request"); 5 requestMap. put ("req_user", users); 6 // save in session Range 7 Map sessionMap = context. getSession (); 8 sessionMap. put ("session_user", users); 9// Saved in the global range of 10Map appMap = context. getApplication (); 11 appMap. put ("app_user", users );        


 2. Access Servlet API in IoC Mode

In the above Code, the scope objects of request, session, and application are all obtained by the Action class. This practice is characterized by the fact that the Code for getting objects and using objects is placed in a class, another way is to keep the code that uses these objects only in the Action class, and to get the code of the object is implemented by Struts2, struts2 obtains these objects and injects them into the Action class, which can be used by the Action class. This implementation idea is the famous IoC. It can separate the code for getting objects and using objects, so that the system can further "decouple and ".

The Code is as follows:

 1 public class UserAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware{ 2  3     private Map<String, Object>request; 4     private Map<String, Object>session; 5     private Map<String, Object>application; 6  7     @Override 8     public void setApplication(Map<String, Object>application) { 9         // TODO Auto-generated method stub10         this.application=application;11     }12     @Override13     public void setSession(Map<String, Object> session) {14         // TODO Auto-generated method stub15         this.session=session;16     }17     @Override18     public void setRequest(Map<String, Object> request) {19         // TODO Auto-generated method stub20         this.request=request;21     }22 }

In the code above, Action implements the RequestAware, SessionAware, and ApplicationAware interfaces, so that Struts2 can inject request, session, and application objects to the Action. Take session as an example. Struts2 gets the session object. After a UserAction object is created, Struts2 checks whether UserAction has implemented the SessionAware interface. If yes, it calls Useraction.

And pass the session as a parameter to this method. The "this. the seesion = session code saves the session as a member variable, so that the session object is injected.

 3. Servlet API coupling access method

Obtain the ServletAPI object through the ServletActionContext class

     Strutes2 provides ServletActionContext to obtain the original Servlet API

ServletActionContext getServletContext ();


HttpServletResponse getResponse ();


HttpServletRequest getRequest ();

Get the session object through request. getSession ()


Set the value through xxx. setAttribute ()

The Code is as follows:

1         HttpServletRequest request=ServletActionContext.getRequest();2         HttpServletResponse response=ServletActionContext.getResponse();3         HttpSession session=request.getSession();4         ServletContext application=ServletActionContext.getServletContext();5         request.setAttribute("req_user", users);6         session.setAttribute("session_user", users);7         application.setAttribute("app_user",users);


Struts2 Data Validation

Inherit the ActionSupport class to complete Action development

ActionSupport not only implements the Action interface, but also supports verification and localization.

If an error occurs, the system will query the result input page. If the error does not exist, the system will report 404.

        <action name="UserAction" class="" method="reg">            <result name="show" type="dispatcher">/ch01/show.jsp</result>            <result name="input">/ch01/reg.jsp</result>        </action>
Public class HouserUserAction extends ActionSupport {//... the public void validate () {if (uname = null | uname. equals ("") {super. addFieldError ("uname_err", "username required");} if (upwd = null | upwd. equals ("") {super. addFieldError ("upwd_err", "Password required ");}}}

HTML display imported struts2 label <% @ taglib uri ="/Struts-tags"Prefix ="S"%>

<S: fielderror fieldName ="Uname_err"/> The error message is displayed. If the name attribute is not set, all the error messages will be output. Because the struts tag does not pass the fiter filter, the jsp page is not recognized and must be on the web. configure in Xml/* filter all

You can set the Struts tag's own style, or set struts. ui. them In struts to cancel the style.




Related Article

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: 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.