struts2获取Servlet API的两种方法
1.通过ServletActionContext获取
在Action中调用ServletActionContext的静态方法来获取:
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext servletcontext = ServletActionContext.getServletContext();
2.通过注入的方式获取
Struts2框架在运行时,在struts.xml查找匹配的action后,action执行之前,会默认执行一些interceptor,
其中有一个servletConfig的interceptor会判断action类是否实现了一些接口,实现了这些接口,就会将Servlet API注入到action中,如下图所示,此时Action类中的request就获取到了 ServletRequestAware 接口注入的request.
ServletRequestAware 接口可以获取HttpServletRequest
ServletResponseAware 接口可以获取HttpServletResponse
ServletContextAware 接口可以获取ServletContext