Struts2 's Actioncontext && servletactioncontext

Source: Internet
Author: User
Tags constructor requires thread

1. Actioncontext

In STRUTS2 development, in addition to automatically setting the request parameters to the Action field, we often need to get some information about the request or session directly in the action, even the request to Javaservlet HTTP directly ( HttpServletRequest), Response (HttpServletResponse) operation. We need to get the value of request parameter "username" in action: actioncontext context = Actioncontext.getcontext (); Map params = Context.getparameters (); String username = (string) params.get ("username");

Actioncontext (Com.opensymphony.xwork.ActionContext) is the context in which the action executes, and the context can be thought of as a container (in fact, our container here is a map). It holds the object that the action needs to use when it executes. In general, our Actioncontext are through: actioncontext context = (Actioncontext) actioncontext.get (); To get. Let's take a look at the creation of the Actioncontext object here:

static ThreadLocal Actioncontext = new actioncontextthreadlocal ();

Actioncontextthreadlocal is an inner class that implements Threadlocal. Threadlocal can be named "Thread-local variable", which provides a copy of the value of a variable for each thread that uses the variable. Enables each thread to independently change its own copy without conflicting with the copy of the other thread. This way, the properties in our Actioncontext are only visible in the corresponding current request thread, ensuring that it is thread-safe.

Get Httpsession:map Session by Actioncontext = Actioncontext.getcontext (). GetSession ();

2. Servletactioncontext

Servletactioncontext (com.opensymphony.webwork. Servletactioncontext), this class directly inherits from the Actioncontext that we described above, which provides direct access to the servlet-related objects, which can be obtained with the following objects:

(1) Javax.servlet.http.HttpServletRequest:HTTPservlet Request object

(2) Javax.servlet.http.HttpServletResponse:HTTPservlet corresponding object

(3) Javax.servlet.ServletContext:Servlet contextual information

(4) Javax.servlet.ServletConfig:Servlet Configuration Object

(5) javax.servlet.jsp.PageContext:Http page context

How to get the servlet related objects from Servletactioncontext:

<1> get HttpServletRequest object: HttpServletRequest request = Servletactioncontext. Getrequest ();

<2> acquired HttpSession object: HttpSession session = Servletactioncontext. Getrequest (). GetSession ();

3. Servletactioncontext and Actioncontext Contact

Servletactioncontext and Actioncontext have some repetitive functions, how do we choose between action? The principle we follow is that if Actioncontext can achieve our function, it is best not to use servletactioncontext, so that our action does not go directly to the servlet related objects.

Note: There is one thing to note when using Actioncontext: do not use Actioncontext.getcontext () in the action constructor, because some of the values in Actioncontext may not be set , the value obtained by Actioncontext may be null, and httpservletrequest req = Servletactioncontext.getrequest () is also not placed in the constructor. Do not assign a value directly to the Req as a class variable. As for the reason, I think because of the static ThreadLocal Actioncontext = new Actioncontextthreadlocal () mentioned earlier, from here we can see that Actioncontext is thread-safe, And Servletactioncontext inherits from Actioncontext, so Servletactioncontext is also thread-safe, thread safety requires each thread to be independent, so the creation of Req also requires independent, So Servletactioncontext.getrequest () do not put in the constructor, or directly in the class, but should be placed in each specific method body (Eg:login (), Queryall (), insert (), etc.), This ensures that each time an object is created, a req is created independently.

4. Get request, response and session in Struts2

(1) non-IOC mode

Method One: Use the Org.apache.struts2.ActionContext class to get the current action's context object through its static method GetContext ().

Actioncontext CTX = Actioncontext.getcontext (); Ctx.put ("Liuwei", "Andy"); Request.setattribute ("Liuwei", "Andy"); Map session = Ctx.getsession (); Session HttpServletRequest request = Ctx.get (Org.apache.struts2.StrutsStatics.HTTP_REQUEST); HttpServletResponse response = Ctx.get (Org.apache.struts2.StrutsStatics.HTTP_RESPONSE);

Careful friends can find that the session here is a map object, in the Struts2 in the bottom of the session is encapsulated into the map type. We can directly manipulate the map object to write and read the session, without having to manipulate the HttpSession object directly.

Method Two: Use Org.apache.struts2.ServletActionContext class public class useraction extends  actionsupport {         //Other code Snippets           private HttpServletRequest req; //  private httpservletrequest  req = servletactioncontext.getrequest ();  This statement is wrong to place in this position, and it is also wrong to put this statement in the construction method.     public string login ()  {         Req = servletactioncontext.getrequest (); The acquisition of  //req must be achieved in a specific way          user = new user ();         user.setuid (UID);         user.setpassword (password);         if  (userdao.islogin (user))  {             req.getsessiOn (). SetAttribute ("user",  user);             return SUCCESS;         }         return  LOGIN;     }     public string queryall ()  {         req = servletactioncontext.getrequest (); The acquisition of  //req must be achieved in a specific way         ulist = userdao.queryall ();         req.getsession (). SetAttribute ("UList",  ulist);         return SUCCESS;     }          //other code Snippets}

(2) IOC mode (i.e. using STRUTS2 Aware Interceptor)

To use the IOC approach, we will first tell the IOC container (Container) the willingness to acquire an object by implementing the appropriate interface. public class useraction extends actionsupport implements sessionaware,  servletrequestaware, servletresponseaware {    private httpservletrequest  request;      private HttpServletResponse response;       public void setservletrequest (httpservletrequest request)  {         this.request = request;      }      public void setservletresponse (httpservletresponse response)  {         this.response = response;      }      public string execute ()  {           httpsession session = request.getsession ();  &NBsp;       return success;      }}

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.