in order to avoid theServlet APIcoupled together, ConvenientActiondoUnit Test, Struts2theHttpServletRequest, HttpSessionand theServletContextis encapsulated., constructs a3aMapobject to replace this3an Object, in theActioncan be used directly in theHttpServletRequest, HttpSession, ServletContextcorresponding to theMapobject to save and read data. Here, everybody, look.Struts1is not provided withServletof theAPIDecoupled .
1.struts2 How to get request, response, session, ServletContext
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. STRUTS2 provides three ways to get these objects, as described below;
non-IOC method:The implementation is decoupled from the
servlet by direct acquisition of the Actioncontext,servletactioncontext class
- L actioncontext is the context object that the Action executes , and in actioncontext It holds the All Objects required for action execution, including parameters, request, session, application and so on .
static ThreadLocal Actioncontext = new Actioncontextthreadlocal ()
(Actioncontext) Actioncontext.get (); to get
- LGetHttpServletRequestcorresponding to theMapObject:public object get (Object key): ActioncontextThe class does not provide a similargetrequest ()such a way to getHttpServletRequestcorresponding to theMapObject. to getHttpServletRequestcorresponding to theMapObject, can beimplemented by passing the "request" parameter for the Get () method
Actioncontext.get (Org.apache.struts2.StrutsStatics.HTTP_REQUEST);
- Get HttpServletResponse, which is similar to request;
Actioncontext.get (Org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
- L Get the map object for HttpSession :
Public Map getsession ()
- L Get the map object for ServletContext :
Public Map getapplication ()
test code: Get Request,response,session,application Object
@SuppressWarnings ("Serial") Public classContextactionextendsactionsupport{@Override PublicString Execute ()throwsException {System.out.println ("Welcome to the Execute method in Contextaction!"); /**Request object (the way it is decoupled from Servletapi)*//*Actioncontext.getcontext (). Put ("username", "request_username"); *//**Session object (the way it is decoupled from Servletapi)*//*Actioncontext.getcontext (). GetSession (). Put ("username", "session_username"); *//**Application Object (ServletContext object) (How to decouple from Servletapi)*//*Actioncontext.getcontext (). Getapplication (). Put ("username", "application_username"); */Use with Servletactioncontext to operate the above
Servletactioncontext.getrequest (). SetAttribute ("username", "request_username");
Servletactioncontext.getservletcontext (). SetAttribute ("username", "application_username");
Servletactioncontext.getrequest (). GetSession (). SetAttribute ("username", "session_username");System.out.println ("Request:" +servletactioncontext.getrequest ()); System.out.println ("Response:" +servletactioncontext.getresponse ()); System.out.println ("Session:" +servletactioncontext.getrequest (). getsession ()); System.out.println ("ServletContext:" +Servletactioncontext.getservletcontext ()); //constant success= "SUCCESS" in Action interface returnSUCCESS; }}
IOC method: Implements the specified interface, injected by the struts framework runtime, i.e. using the Struts2 aware interceptor
Action let struts2 action instance injection parameters, request, session and application corresponding to the map object :
Test code:: Get request,response,session,application Object
@SuppressWarnings ("Serial") Public classContextactiontwoextendsActionsupportImplementsServletrequestaware, servletcontextaware,servletresponseaware,sessionaware{PrivateHttpServletRequest request; Privatehttpservletresponse response; PrivateMap<string, object>session; PrivateServletContext Application;//Note that the same functionality can be implemented with interface Applicationaware//Use the second way@Override PublicString Execute ()throwsException {System.out.println ("Welcome to execute () in Contextactiontwo!"); //to store values in scopeRequest.setattribute ("username", "request_username2"); Session.put ("username", "session_username2"); Application.setattribute ("username", "application_username2"); returnSUCCESS; } @Override Public voidSetsession (map<string, object>session) { //TODO auto-generated Method Stub This. session =session; } @Override Public voidSetservletresponse (httpservletresponse response) {//TODO auto-generated Method Stub This. Response =response; } @Override Public voidSetservletcontext (ServletContext context) {//TODO auto-generated Method Stub This. Application =context; } @Override Public voidsetservletrequest (HttpServletRequest request) {//TODO auto-generated Method Stub This. Request =request; }}
attr.jsp
< Body > 123 ${requestscope.username}<br> ${ Sessionscope.username}<br> ${applicationscope.username} <br> </body>
configuration of the Struts-context.xml file:
<Struts> < Packagename= "Context"namespace= "/context"extends= "Struts-default"> <Default-action-refname= "Contextaction_test"></Default-action-ref> <Actionname= "Contextaction_test"class= "Cn.youric.you.two_context." Contextaction "> <resultname= "Success">/context/success.jsp</result> </Action> <Actionname= "Contextaction02_test"class= "Cn.youric.you.two_context." Contextactiontwo "> <resultname= "Success">/context/attr.jsp</result> </Action> </ Package></Struts>
Don't forget the include;
2. Chat Actioncontext
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 New 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, so that each thread can independently change its copy without conflicting with the other thread's copy. So, The properties in our Actioncontext are only visible in the corresponding current request thread, ensuring that it is thread-safe.
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.
STRUTS2 fifth--Struts2 and Servlet API decoupling