在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对象。

 

  1. public class TestAction {  
  2. HttpServletRequest request = ServletActionContext.getRequest();  
  3. HttpServletResponse response = ServletActionContext.getResponse();  
  4. HttpSession session =  request.getSession();  
  5. ActionContext actionContext = ServletActionContext.getActionContext(request);  
  6. ActionContext context = ServletActionContext.getContext();  
  7. ActionMapping mapping = ServletActionContext.getActionMapping();  
  8. PageContext pageContext =  ServletActionContext.getPageContext();  
  9. ServletContext servletContext = ServletActionContext.getServletContext();  
  10. ValueStack valueStack = ServletActionContext.getValueStack(request);  
  11. }  

2.使用ActionContext

  1. public class TestAction {  
  2.     ActionContext context = ActionContext.getContext();  
  3.       
  4.     public void test(){  
  5. ActionInvocation actionInvocation = context.getActionInvocation();  
  6. Locale locale = context.getLocale();  
  7. ValueStack valueStack = context.getValueStack();  
  8. Container container =  context.getContainer();  
  9. Map<String, Object> parameters = context.getParameters();  
  10. Map<String, Object> session = context.getSession();  
  11. Map<String, Object> application = context.getApplication();  
  12. Map<String, Object> contextMpap = context.getContextMap();  
  13. Map<String, Object> conversionErrorss = context.getConversionErrors();  
  14.     }  
  15.       
  16. }  

 

posted @ 2015-12-18 20:14  杀出重围啊  阅读(241)  评论(0编辑  收藏  举报