-1

I have a filter class for which I am using try with resources in java7. But I need to implement this in java6. I need help in writing the equivalent code in java6 for this:

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);
    }
}
techspider
  • 3,370
  • 13
  • 37
  • 61

1 Answers1

0

Look here for a good answer with Lombok library similar question However if you just want pure java solution: Try with resources only was added in Java 7 so here is a proper java 6 solution

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
      }
    }
Community
  • 1
  • 1
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36