How to manually get parameters by action in Struts 2

Source: Internet
Author: User
Tags constructor requires thread

Struts2 action to get session,jsp page parameters manually

1. Actioncontext

In STRUTS2 development, in addition to automatically setting the request parameters to the Action field, we often need to get some information directly from the request or conversation (session) in the action.

You even need to directly respond to Javaservlet HTTP requests (HttpServletRequest), Response (HttpServletResponse) operations.

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");

In the context of execution, the context can be thought of as a container (in fact our container is just a map) that holds the object that the action needs to execute.

In general, our Actioncontext are obtained by: actioncontext context = (Actioncontext) actioncontext.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 the Threadlocal.

Threadlocal can be named thread local variable, which provides a copy of the variable value for each thread that uses the variable, so that each thread can change its own copy independently.

It does not conflict with replicas of other threads. In this way, the attributes in our Actioncontext are only visible in the corresponding current request thread, 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,

It provides the ability to access directly to the servlet-related objects, and it can get objects that are:

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

More Wonderful content: http://www.bianceng.cn/Programming/Java/

Note: There is one thing to note when using Actioncontext: Do not use Actioncontext.getcontext () in the constructor of the action, because some values in Actioncontext may not be set at this time,

The value obtained by actioncontext may be null;

Similarly, httpservletrequest req = Servletactioncontext.getrequest () should not be placed in the constructor, nor can the Req be assigned a value 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 or directly in the class.

Instead, it should be placed in each specific method body (Eg:login (), Queryall (), insert (), etc.) to ensure that each time an object is generated, a req is built 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 fragment  
          
    private HttpServletRequest req;  
    Private HttpServletRequest req = Servletactioncontext.getrequest (); It is wrong to place this statement in this position, and it is also wrong to place this statement in the construction method. Public  
      
    String Login () {  
        req = Servletactioncontext.getrequest ();//req's acquisition must implement  
        user = new User () in a specific method;  
        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 ();//req's acquisition must be implemented in a specific method  
        Ulist = Userdao.queryall ();  
        Req.getsession (). setattribute ("Ulist", ulist);  
        return SUCCESS;  
    }  
          
    Additional code fragment  
}

(2) IOC approach (i.e. using 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 ();  
        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.