Changes between Initial Version and Version 1 of 2017_1


Ignore:
Timestamp:
01/16/2017 01:09:29 PM (9 years ago)
Author:
wuyuanbo
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • 2017_1

    v1 v1  
     11.java类中EnvUtils使用优化 
     2  在Env实例依赖servlet的过滤器,其功能也主要是用于处理servlet请求的工具类,在非Controller类或jsp中使用可能会造成错误。 
     3 
     4{{{ 
     5//evn过滤器代码 org.gelivable.web.EnvFilter : 62 
     6public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
     7            throws IOException, ServletException { 
     8        ...... 
     9        Env env = EnvUtils.getEnv(); 
     10        envMap.put(env, ""); 
     11        try { 
     12            //下面三个变量只有servlet处理请求时才会被实例化 
     13            env.setRequest((HttpServletRequest) request); 
     14            env.setResponse((HttpServletResponse) response); 
     15            env.setServletContext(servletContext); 
     16 
     17            request.setAttribute("env", env); 
     18 
     19            chain.doFilter(request, response); 
     20 
     21        }  
     22        ...... 
     23    } 
     24}}} 
     25在聚超值项目中,entity类(service偶尔也会出现)中经常会用env获取service或dao类实例的代码。 
     26 
     27{{{ 
     28public class User { 
     29        ...... 
     30        public UserPurchasingInfo getInfo() { 
     31                ...... 
     32                info = EnvUtils.getEnv().getBean(GeliDao.class).find(UserPurchasingInfo.class, this.userId); 
     33                ...... 
     34        } 
     35        ...... 
     36} 
     37}}} 
     38这种代码至少在三种情况下调用会出现错误:[[BR]] 
     391.在单元测试中[[BR]] 
     402.不依赖于servlet的定时任务中[[BR]] 
     413. 
     42{{{ 
     43public class EnvUtils { 
     44    public static Env getEnv() { 
     45        return threadLocal.get(); 
     46    } 
     47 
     48    public static void removeEnv() { 
     49        threadLocal.remove(); 
     50    } 
     51 
     52    //通过EnvUtils获取的Env实例是线程单例的 
     53    private static final ThreadLocal<Env> threadLocal = new ThreadLocal<Env>() { 
     54        @Override 
     55        protected Env initialValue() { 
     56            return new Env(); 
     57        } 
     58    }; 
     59 
     60} 
     61}}} 
     62