Differences between servletactioncontext and actioncontext in struts2

Source: Internet
Author: User

1. actioncontext

In struts2 development, in addition to automatically setting request parameters to the action field, we often need to directly obtain information about the request or session in the action, you even need to directly request the assumervlet HTTP (httpservletrequest) and respond to (httpservletresponse) operations. we need to obtain the value of the request parameter "username" in the action:

  1. Actioncontext context = actioncontext. getcontext ();
  2. Map Params = context. getparameters ();
  3. String username = (string) Params. Get ("username ");

Actioncontext (COM. opensymphony. xwork. actioncontext) is the context of Action execution,The context can be viewed as a container.(In fact, our container here is just a map.) It stores the objects required for action execution. In general, our actioncontext uses:
Actioncontext context = (actioncontext) actioncontext. Get (); To get it. Let's take a look at the creation of the actioncontext object here:

Static threadlocal actioncontext = new actioncontextthreadlocal ();

Actioncontextthreadlocal is an internal class implementing threadlocal. threadlocal can be named "Thread Local variable". It provides a copy of the variable value for every thread that uses this variable, so that each thread can change its own copy independently, it does not conflict with copies of other threads. in this way, the attributes in our actioncontext will only be visible in the corresponding current request thread to ensure thread safety.

Httpsession: Map session = actioncontext. getcontext (). getsession ();

2. servletactioncontext

Servletactioncontext (COM. opensymphony. webwork. servletactioncontext), this class directly inherits the actioncontext we introduced above, which provides the function of directly accessing servlet-related objects. The objects it can obtain include:

(1) javax. servlet. http. httpservletrequest: httpservlet request object

(2) javax. servlet. http. httpservletresponse: corresponding object of httpservlet

(3) javax. servlet. servletcontext: servlet context information

(4) javax. servlet. servletconfig: servlet configuration object

(5) javax. servlet. jsp. pagecontext: HTTP Page Context

How to obtain servlet-related objects from servletactioncontext:

<1> get the httpservletrequest object: httpservletrequest request = servletactioncontext. getrequest ();

<2> obtain the httpsession object: httpsession session = servletactioncontext. getrequest (). getsession ();

3. Contact servletactioncontext and actioncontext

Servletactioncontext and actioncontext have some repeated functions. In our actions, how should we choose?The principle we follow is: If actioncontext can implement our functions, it is best not to use servletactioncontext, so that our actions do not directly access servlet-related objects.

Note: When Using actioncontext, note the following:
Do not use actioncontext. getcontext () in the Action constructor (),
Because some values in actioncontext may not be set at this time, the value obtained through actioncontext may be null;Similarly, httpservletrequest Req = servletactioncontext. getrequest () should not be placed in the constructor, nor should req be directly assigned to it as a class variable.As for the reason, I think it is because of the static threadlocal actioncontext mentioned above.
= New actioncontextthreadlocal (). here we can see that actioncontext is thread-safe, while servletactioncontext inherits from actioncontext. Therefore, servletactioncontext is thread-safe. thread security requires that each thread be independent, therefore, req must be created independently, so servletactioncontext. the getrequest () statement should not be placed in the constructor, nor directly in the class, but in each specific method body (eg: Login (), queryall (), insert (), so as to ensure that each time an object is generated, a req is created independently.

4. GET request, response, and session in struts2

(1) Non-IOC Mode

Method 1: Use the org. Apache. struts2.actioncontext class to obtain 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, and the underlying sessions in struts2 are encapsulated into the map type.

We can directly operate on this map object to write and read sessions, instead of directly operating on the httpsession object.

Method 2: Use the org. Apache. struts2.servletactioncontext class

Public class useraction extends actionsupport {// other code snippets private httpservletrequest req; // Private httpservletrequest Req = servletactioncontext. getrequest (); it is wrong to place this statement in this position. It is also wrong to put this statement in the constructor method. Public String login () {Req = servletactioncontext. getrequest (); // obtain Req. The user = new user (); user must be implemented in the specific method. setuid (UID); User. setpassword (password); If (userdao. islogin (User) {req. getsession (). setattribute ("user", user); Return success;} return login;} Public String queryall () {Req = servletactioncontext. getrequest (); // obtain Req. You must implement ulist = userdao in the specific method. queryall (); req. getsession (). setattribute ("ulist", ulist); Return success;} // other code snippets}

(2) IOC (that is, struts2 aware interceptor)

To use the IOC method, we must first tell the IOC container (container) The willingness to obtain an object and implement the corresponding interface to achieve this.

    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();             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.