javaservletsservlet-filters

Servlet filter for caching


I'm creating a servlet filter for caching. The idea is to cache the response body to memcached. The response body is generated by (result is a string):

 response.getWriter().print(result);

My question is that, since the response body will be put into the memcached without modification, do I still need to create a customized HttpServletResponseWrapper? Can anyone provide any skeleton code for this filter?


Solution

  • You need to be able to capture the servlet's output in your filter.

    For this, you need to inject a customized HttpServletResponseWrapper that collects all output sent to getWriter().print() somewhere so that you can hand it off to memcached.

    Maybe something along the lines of:

    ByteArrayOutputStream baos = new ByteArrayOutputStream(3000); 
    final PrintWriter w = new PrintWriter(new OutputStreamWriter(baos, "UTF-8"));
    
    HttpServletResponse wrapper = new HttpServletResponseWrapper(response) {
    
        @Override
        public PrintWriter getWriter() throws IOException {
            return w;
        }
    
    };
    

    If this is a bigger project and you have more control over the network infrastructure, it might also be a good idea to not do this in Java, but just use a separate proxy server in front of the Servlet container. You can control what should be cached by the usual Cache-Control HTTP headers (which you can set using a filter if the servlet does not already do it).