在Action中获取servlet API
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();
- }
- }