Struts 2 Servlet API
Struts 2 encapsulates Servlet APIs, which are more independent from the business layer. There are two ways to call Servlet APIs such as Request and Response.
Static Method Using ServletActinContext
Struts 2 uses ServletActinContext to maintain Servlet objects. ServletActinContext uses ThreadLocal to maintain Servlet objects of different threads. Therefore, ServletActinContext can be used to obtain various Servlet objects.
import org.apache.struts2. ServletActinContext;public class LoginActin extends ActionSupport{ public String login(){ HttpServletRequest request = ServletActinContext.getRequest(); HttpServletResponse response = ServletActinContext.getResponse(); HttpServletContext context = ServletActinContext.getServletContext(); HttpSession session = request.getSession(); …… } }
Use relevant Aware Interfaces
When Struts 2 instantiates an Action instance, if it finds that it implements the relevant Aware interface, it will inject the corresponding resources through the Aware interface method. The Aware interface is actually an interceptor.
The Aware interfaces of Servlet API common objects such as application, request, response, and session are ServletContextAware, ServletRequestAware, ServletResponseAware, and SessionAware respectively.
Public class ServletAwareActionextends ActionSupport extends, ServletRequestAware, ServletResponseAware, SessionAware {private HttpServletRequest request; private HttpServletResponse response; private HttpServletContext application; private HttpSession session; // corresponding setter method public void setServletRequest (HttpServletRequest request) {this. request = request;} public void setServletResponse (HttpServletResponse response) {this. reponse = reponse;} public void setServletContext (HttpServletContext application) {this. application = application;} public void setSession (Map sessionValues) {this. session = sessionValues;} // then these objects can be directly used in the Action to execute () {request. getRemoteAddr (); response. getContentType () session. get ("account"); return SUCCESS ;}}