2016-09-29 59 views
-1

我有一個過濾器類,我正在使用它嘗試使用java7中的資源。但我需要在java6中實現這一點。我需要幫助中的Java6編寫等效代碼如下:嘗試使用java中的等效資源6

public final class YourContext implements AutoCloseable { 

    private static ThreadLocal<YourContext> instance = new ThreadLocal<>(); 

    private HttpServletRequest request; 
    private HttpServletResponse response; 

    private YourContext(HttpServletRequest request, HttpServletResponse response) { 
     this.request = request; 
     this.response = response; 
    } 

    public static YourContext create(HttpServletRequest request, HttpServletResponse response) { 
     YourContext context = new YourContext(request, response); 
     instance.set(context); 
     return context; 
    } 

    public static YourContext getCurrentInstance() { 
     return instance.get(); 
    } 

    @Override  
    public void close() { 
     instance.remove(); 
    } 

    public HttpSession getSession() { 
     return request.getSession(); 
    } 

    // ... (add if necessary more methods here which return/delegate the request/response).  
} 



@Override 
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { 
    HttpServletRequest request = (HttpServletRequest) req; 
    HttpServletResponse response = (HttpServletResponse) res; 

    try (YourContext context = YourContext.create(request, response)) { 
     chain.doFilter(request, response); 
    } 
} 

回答

0

在這裏尋找與龍目島庫一個很好的答案similar question 但是如果你只是想純粹的Java解決方案:只在Java 7中添加的資源嘗試這樣這裏是一個合適的java 6解決方案

YourContext context; 
    try { 
     context = YourContext.create(request, response); 
     chain.doFilter(request, response); 
    } finally { 
     try { 
     context.close(); 
     } catch(Exception e) { 
     //Print error into log or do any error handling you wish to do 
     } 
    }