Struts2 notes -- Action access Servlet API, struts2 -- action
Generally, the Servlet APIs that Web applications need to access are HttpServletRequest, HttpSession, and ServletContext. These three interfaces represent the request, session, and application in the embedded JSP object respectively.
1. Use the ActionContext class provided by Struts2 to access the Servlet API. Below are several common methods contained in the ActionContext class.
Object get (Object key): This method is similar to calling the getAttribute (String name) method of HttpServletRequest.
Map getApplication (): returns a Map object that simulates the ServletContext instance of the application.
Static ActionContext getContext (): obtains the system's ActionContext instance by using the static method.
Map getParameters (): gets all request parameters. Similar to calling the getParameterMap () method of the HttpServletRequest object.
Map getSession (): returns a Map object that simulates an HttpSession instance.
Void setApplication (Map application): directly input a Map instance and convert the key-value pair in the Map instance to the attribute name and attribute value of the application.
Void setSession (Map session): directly transmits a Map instance and converts the key-value pair in the Map instance to the attribute name and attribute value of the session.
Eg:
Set application range attributes through ActionContext
ActionContext ctx = ActionContext.getContext(); ctx.getApplication.put("name","aaa");
Set the attribute of the request range through ActionContext
ctx.put("name","bbb");
2. Although Struts2 provides ActionContext to access the Servlet API, this access is not an instance that directly obtains the Servlet API. to directly access the Serlvet API in the Action, struts2 provides the following interfaces::
ServletContextAware: The Action that implements this interface can directly access the ServletContext instance of the Web application.
ServletRequestAware: The Action that implements this interface can directly access the HttpServletRequest instance requested by the user.
ServletResponseAware: The Action that implements this interface can directly access the HttpSerlvetResponse instance of the server response.
3. Access the Servlet API using ServletActionContext
To directly access the Servlet API, Struts2 also provides a ServletActionContext tool class, which includes the following static methods.
Static PageContext getPageContext (): gets the PageContext object of the Web application.
Static HttpServletRequest getRequest (): gets the HttpServletRequest object of the Web application.
Static HttpServletResponse getResponse (): gets the HttpServletResponse object of the Web application.
Static ServletContext getServletContext (): gets the ServletContext object of the Web application.