zoukankan      html  css  js  c++  java
  • 在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. }  
  • 相关阅读:
    MongoDB学习:(一)MongoDB安装
    事件轮询 Event Loop
    常见的HTML5语义化标签
    前端动画性能优化方案
    前端动画的实现
    《SVN的操作流程及规范》
    css、js文件后的后缀作用是什么?
    实现单行文字溢出显示...,以及多行文字溢出显示...
    从输入URL到页面返回的过程详解
    jQuery实现点击复制效果
  • 原文地址:https://www.cnblogs.com/kangyu222/p/5058127.html
Copyright © 2011-2022 走看看