Struts2 's Actioncontext && servletactioncontext

Source: Internet
Author: User
Tags constructor

1. Actioncontext

In STRUTS2 development, in addition to automatically setting request parameters to action fields, we often need to get some information directly from the action (request) or session (sessions), or even directly to Javaservlet HTTP requests ( HttpServletRequest), Response (HttpServletResponse) operation. We need to get the value of the request parameter "username" in the 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 is executed, and the context can be considered a container (in fact, our container here is just 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 internal class that implements Threadlocal. Threadlocal can be named "Thread local variable", which provides a copy of the variable value for each thread that uses the variable. Enables each thread to change its own copy independently of the other thread, without conflicts with other threads. In this way, the attributes in our Actioncontext are only visible in the corresponding current request thread, thus ensuring that it is thread-safe.

by Actioncontext get Httpsession:map session = Actioncontext.getcontext (). GetSession ();

2. Servletactioncontext

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

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

(2) Javax.servlet.http.HttpServletResponse:HTTPservlet the 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 relevant servlet objects from Servletactioncontext:

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

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

3. Servletactioncontext and Actioncontext Contact

Servletactioncontext and Actioncontext have some repetitive functions, in our action, how to choose? The principle we follow is: if Actioncontext can achieve our function, it is best not to use servletactioncontext, so that our action as far as possible not to directly access the servlet related objects.

Note: There is one thing to note when using Actioncontext: do not use Actioncontext.getcontext () in the constructor of the action, because at this time some values in Actioncontext may not be set , the value obtained by Actioncontext may be null, and likewise, httpservletrequest req = Servletactioncontext.getrequest () should not be placed in the constructor, Also do not assign req directly 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-safe requires each thread to be independent, so the creation of req requires independence, So Servletactioncontext.getrequest () should not be placed in the constructor, nor placed 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. Access to request, response and session in Struts2

(1) non-IOC mode

Method One: Use the Org.apache.struts2.ActionContext class to get the context object of the current action 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 of 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 in this position, and it is also wrong to place this statement in the construction method.     public string login ()  {         Req = servletactioncontext.getrequest ()  //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; &NBSP;&NBSP;&NBSP;&NBSP}     public string queryall ()  {         req = servletactioncontext.getrequest () the acquisition of  //req must be achieved in a specific method         ulist = userdao.queryall ();         req.getsession (). setattribute ("Ulist",  uList);         return SUCCESS; &NBSP;&NBSP;&NBSP;&NBSP}          //other code fragment}

(2) IOC Way (that is, using the Struts2 aware Interceptor)

To use the IOC approach, we first tell the IOC container (Container) that it wants to acquire an object, and do so 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;     &nbsp}}

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.