There are two ways to get these objects in Struts2
1. Non-IOC mode
To obtain the above object, the Com.opensymphony.xwork2.ActionContext class is in key Struts 2. We can get the context object of the current action through its static method GetContext (). With this object, we want to get a few other objects.
Actioncontext CTX = Actioncontext.getcontext ();
Map session = Ctx.getsession ();
Careful friends can find that the session here is a map object in the Struts2 the bottom of the session is encapsulated into the map type we can directly manipulate the map to write and read the session without having to directly manipulate the HttpSession object
In addition, Org.apache.struts2.ServletActionContext is a helper class that can help you get these objects quickly and easily.
HttpServletRequest request = Servletactioncontext.getrequest ();
HttpServletResponse response = Servletactioncontext.getresponse ();
HttpSession session = Request.getsession ();
If you just want to access the session's properties (Attribute), you can also get or add the session range (Scoped) object through Actioncontext.getcontext (). GetSession ().
2, the IOC way (this way is also implemented in tapestry)
To use the IOC approach, we will first tell the IOC container (Container) the willingness to acquire an object by implementing the appropriate interface. Specific implementation
Publicclass Iocservlet extends Actionsupport implementsSessionaware, Servletrequestaware, Servletresponseaware{
Private String message;
Private Map att;
private HttpServletRequest request;
Private HttpServletResponse response;
Public String GetMessage () {
return message;
}
Publicvoid setsession (Map att) {
This.att = att;
}
Publicvoid setservletrequest (HttpServletRequest request) {
This.request = Request;
}
Publicvoid Setservletresponse (httpservletresponse response) {
This.response = response;
}
@Override
Public String execute () {
Att.put ("msg", "Hello World from session!");
HttpSession session = Request.getsession ();
StringBuffer SB =new StringBuffer ("Message from Request:");
Sb.append (Request.getparameter ("MSG"));
Sb.append ("
Response Buffer Size: ");
Sb.append (Response.getbuffersize ());
Sb.append ("
Session ID: ");
Sb.append (Session.getid ());
message = Sb.tostring ();
return SUCCESS;
}
}
Configuring interceptors in the Struts.xml action
<interceptor-ref name= "ServletConfig" ></interceptor-ref>
Get request response Session object in STRUTS2 action