开发者

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开发者_C百科 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?


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 headers (which you can set using a filter if the servlet does not already do it).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜