Struts Learning Notes (iii) three ways to obtain request, response, and session in Struts2

Source: Internet
Author: User

Three ways to 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 (); Sessionhttpservletrequest  request = Ctx.get (Org.apache.struts2.StrutsStatics.HTTP_REQUEST); HttpServletResponse response = Ctx.get (Org.apache.struts2.StrutsStatics.HTTP_RESPONSE);

A careful friend can find this place.Sessionis aMapObject,in theStruts2The bottom of theSessionhave been encapsulated as aMaptype.we can do this directly .Mapobject to theSessionthe Write and read operations,Without having to operate directly.HttpSessionObject.

method two Span style= "font-size:7.5pt" >: Use

public class Useraction extends Actionsupport {          //other code Snippets      private HttpServletRequest requset;   Private HttpServletRequest Requset = Servletactioncontext.getrequest (); It is wrong to place this statement in this position, and it is also wrong to put this statement in the constructor. Public    String Login () {         requset = Servletactioncontext.getrequest ();//Requset The acquisition must be implemented in a specific way         user = new User ();         User.setuid (UID);         User.setpassword (password);         if (userdao.islogin (user)) {             requset.getsession (). SetAttribute ("user", user);             return SUCCESS;         }         return LOGIN;     }     Public String Queryall () {         requset = Servletactioncontext.getrequest ();//Requset's acquisition must be implemented in a specific method         UList = Userdao.queryall ();         Requset.getsession (). SetAttribute ("UList", uList);         return SUCCESS;     }     Other Code Snippets}

(2) IoC way ( struts2 Aware interceptor )

you want to use IoC way that we first have to tell IoC Container (Container) want to get the intention of an object, by implementing the corresponding interface to do this.

public class Baseaction 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;     } }

Additional notes: Servletactioncontext and Actioncontext Contact

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 the 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 aActionthe context at execution time,context can be thought of as a container(in fact, our container here is aMaponly),it is stored inActionobjects that need to be used at execution time.General Situation,of ourActioncontextIt's all through .:Actioncontext context = Actioncontext.getcontext ();to get the.Let's take a look at this.ActioncontextCreation of Objects:

static ThreadLocal Actioncontext = new actioncontextthreadlocal ();

actioncontextthreadlocalis to achieveThreadLocalan inner class of. ThreadLocalcan be named"Thread Local Variables",it provides a copy of a variable value for each thread that uses the variable,enables each thread to independently change its own copy,without conflicting copies of other threads.this,we areActioncontextwill only be visible in the corresponding current request thread .,so that it is thread-safe.

through Actioncontext Get HttpSession:

Map session = Actioncontext.getcontext (). GetSession ();

2. Servletactioncontext

ServletActi Oncontext (Com.opensymphony.webwork.ServletActionContext), This class directly inherits from what we described above actioncontext, It provides direct and servlet functions related to object access The object it can get is :

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

(5) Javax.servlet.jsp.PageContext : Http Page Context

how to get from Servletactioncontext Made in Servlet the related objects :

<1> Get HttpServletRequest Object : 

HttpServletRequest request = Servletactioncontext.getrequest ();

<2> Get HttpSession Object :

HttpSession session = Servletactioncontext.getrequest (). GetSession ();

Servletactioncontextand theActioncontextthere are some repetitive functions in ourActionin,how to make the choice??The principle we follow is: if actioncontext can achieve our function , It is best not to use Servletactioncontext, Let our Action try not to go directly to the Servlet 's related objects .

Note: When usingActioncontextone thing to note when:not inActionconstructor used in theActioncontext.getcontext (), because this timeActioncontextsome of the values may not be set,then throughActioncontextthe value obtained may beNULL; Similarly,httpservletrequestreq = servletactioncontext.getrequest ()Do not put it in a constructor, or directlyreqassign a value to it as a class variable. As for the reason, I think it's becausestatic ThreadLocal Actioncontext = new Actioncontextthreadlocal (), from here we can seeActioncontextis thread-safe, andServletactioncontextinherit fromActioncontext, soServletactioncontextalso thread-safe, thread-safe requires each thread to be independent, soreqIs also required to be created independently, soservletactioncontext.getrequest ()this sentence should not be placed in the constructor, nor directly in the class, but should be placed in each specific method body(eg:Login (),Queryall (),Insert ()wait)To ensure that each time the object is created, a separatereq.


Struts Learning Notes (iii) three ways to obtain request, response, and session in Struts2

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.