Struts2的Action组件是不依赖servlet API 的。那么当你在action中的业务需要处理HttpServletRequest和HttpServletResponse的时候(比如要对响应做处理写cookie,生成验证码)怎么办呢?
有3种办法可以实现action中获取servlet api
1.使用ServletActionContext的静态方法
Struts2使用ServletActionContext对象维护Servlet api 对象(像request,response,session,application)。ServletActionContext使用ThreadLocal(线程局部变量,关于ThreadLocal请参看本博另一篇文章《理解TheadLocal(线程局部变量)》),这样能保证获取的是当前用户当前线程的servlet api对象。
public class TestAction { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); HttpSession session = request.getSession(); ActionContext actionContext = ServletActionContext.getActionContext(request); ActionContext context = ServletActionContext.getContext(); ActionMapping mapping = ServletActionContext.getActionMapping(); PageContext pageContext = ServletActionContext.getPageContext(); ServletContext servletContext = ServletActionContext.getServletContext(); ValueStack valueStack = ServletActionContext.getValueStack(request); }
2.使用ActionContext
public class TestAction { ActionContext context = ActionContext.getContext(); public void test(){ ActionInvocation actionInvocation = context.getActionInvocation(); Locale locale = context.getLocale(); ValueStack valueStack = context.getValueStack(); Container container = context.getContainer(); Map<String, Object> parameters = context.getParameters(); Map<String, Object> session = context.getSession(); Map<String, Object> application = context.getApplication(); Map<String, Object> contextMpap = context.getContextMap(); Map<String, Object> conversionErrorss = context.getConversionErrors(); } }
3.使用Struts2的资源注入拦截器
让你的action继承几个接口,实现他们的方法,然后声明serlvet api对象的变量就行了,在运行时struts2会把相对的对象注入到你的变量中。
这种注入不用多解释肯定是拦截器实现的啦!
而且值得注意的是session的接收变量是一个map而不是httpsession
public class TestAction implements ServletContextAware,ServletRequestAware,ServletResponseAware,SessionAware { private ServletContext servletContext; private HttpServletRequest request; private HttpServletResponse response; private Map<String, Object> session; /***实现相应接口的方法******/ public void setServletContext(ServletContext arg0) { this.servletContext = arg0; } public void setServletRequest(HttpServletRequest arg0) { This.request = arg0; } public void setServletResponse(HttpServletResponse arg0) { This.response = arg0; } public void setSession(Map<String, Object> arg0) { This.sessoin = arg0; } }