Struts2 Study Notes (5) -- Action access Servlet API, struts2servlet
There are three methods to access Servlet APIs in Strut2:
1. Using ActionContext to access the Servlet API is recommended. However, this solution does not obtain the actual Servlet API.
Steps:
1) Create an ActionContext
- ActionContext context = ActionContext. getContext ();
2). Get the Servlet API through the context object
- Map <String, Object> getApplication () obtains all information stored in the application.
- Map <String, Object> getParameters () is equivalent to request. getParameterMap ();
- Map <String, Object> getSession (); obtains all the information stored in the session.
- Put (String key, Object value); is equivalent to request. setAttribute ();
- Object get (String key) is equivalent to request. getAttribute ();
2. Inject (real Servlet API)
Use the * Aware interface to obtain the Servlet API, for example:
- ServletContextAware: injects the ServletContext object
- ServletRequestAware: injects the request object
- ServletResponseAware: injects a response object.
For example, to obtain the HttpServletRequest object:
1 public class TestAction extends ActionSupport implements ServletRequestAware { 2 HttpServletRequest request; 3 @Override 4 public String execute() { 5 request.setAttribute("name", "requestTest"); 6 return "success"; 7 } 8 9 @Override10 public void setServletRequest(HttpServletRequest request) {11 this.request = request;12 }13 14 }
3. Use ServletActionContext (real Servlet API)
Through the static method provided in the ServletActionContext class, you can directly obtain the Servlet API:
1 // obtain request2 HttpServletRequest request = ServletActionContext. getRequest (); 3 // get session4 HttpSession session = request. getSession (); 5 // get context6 ServletContext context = ServletActionContext. getServletContext ();