Access servlet API in struts2, struts2servlet
The Action in Struts2 is not coupled with any Servlet API, but it is almost impossible for the WEB application controller to access the Servlet API, such as tracking the HTTP Session status. The ActionContext class is provided in Struts2. The Action class of Struts2 can be used to access the Servlet API.
The ActionContext class contains several common methods:
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 (): Static method to obtain the ActionContext instance of the system.
Map getParameters (): Get 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 to convert the key-value pair in the Map instance to the attribute name and attribute value of the application.
Void setSession (Map session): Directly input a Map instance to convert the key-value pair in the Map instance to the attribute name and attribute value of the session.
Example:
Public class TextAction implements Action {
Public String execute () throws Exception {
ActionContext ctx = ActionContext. getContext (); // get the ActionContext instance
Integet counter = (Integer) ctx. getApplication (). get ("counter"); // get the attribute value in the application range
Return SUCCESS;
}
}
Although struts2 provides ActionContext to access the Servlet API, this access is not an instance that directly obtains the servlet API. To access the Servlet API in the Action, struts2 also 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 of the WEB application.
ServletResponseAware: The Action that implements this interface can directly access the HttpServletResponse instance responded by the server.
In addition, to directly access Servlet APIs, struts2 also provides a ServletActionContext tool class, which includes the following static methods:
Static PageContext getPageContext (): Get the PageContext object of the WEB application.
Static HttpServletRequset getRequets (): Obtain the HttpServletRequset object of the Web application.
Static HttpServletRsponse getResponse (): Obtain the HttpServletResponse object of the WEB application.
Static ServletContext getServletContext (): Obtain the ServletContext object of the WEB application.