(i) Through Actioncontext
To avoid coupling with the Servlet API to facilitate unit testing of the action class, Struts 2 encapsulates HttpServletRequest, HttpSession, and ServletContext. Three map objects were constructed to replace these three objects, and in action, the map objects corresponding to the HttpServletRequest, HttpSession, and ServletContext are used to save and read data directly. These three objects can be obtained through the Com.opensymphony.xwork2.ActionContext class. Actioncontext is the context of action execution and holds many objects such as parameters, request, session, application, and locale. The way to get a map object through the Actioncontext class is:
public class TestAction1 extends actionsupport{
private map<string,object> request;
Private Map<string, object> session;
Private map<string, object> application;
Public TestAction1 () {
TODO auto-generated Constructor stub
This.request = (MAP) actioncontext.getcontext (). Get ("request");
This.session = Actioncontext.getcontext (). GetSession ();
This.application = Actioncontext.getcontext (). Getapplication ();
}
}
(ii) Control reversal
The action class has another way to get Servletapi, which is that we can let him implement certain interfaces so that the STRUTS2 framework injects the request, session, and application objects to the action instance at run time. This is the way to control the reversal, and the corresponding three interfaces and their methods are as follows:
public class TestAction2 extends Actionsupport implements Requestaware, sessionaware,applicationaware{
Private static final long serialversionuid = 1L;
private map<string,object> request;
Private Map<string, object> session;
Private map<string, object> application;
@Override
public void Setapplication (map<string, object> application) {
TODO auto-generated Method Stub this.application = Application;
}
@Override
public void Setsession (Map<string, object> session) {
TODO auto-generated Method Stub
This.session = session;
}
@Override
public void Setrequest (map<string, object> request) {
TODO auto-generated Method Stub
This.request = Request;
}
Public TestAction2 () {//TODO auto-generated constructor stub}
@Override
Public String Execute () throws Exception {
TODO auto-generated Method Stub
System.out.println ("TestAction2 execute ...");
This.request.put ("Reqattr", "Reqdirect");
This.session.put ("Sessionattr", "Sessiondirect");
This.application.put ("Applicationattr", "Applicationdirect");
return SUCCESS; }
}
How SERVLETAPI Gets the map type in struts