简体   繁体   English

用于缓存的Servlet过滤器

[英]Servlet filter for caching

I'm creating a servlet filter for caching. 我正在为缓存创建一个servlet过滤器。 The idea is to cache the response body to memcached. 我们的想法是将响应主体缓存到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? 我的问题是,由于响应主体将在没有修改的情况下放入memcached,我还需要创建一个自定义的HttpServletResponseWrapper吗? Can anyone provide any skeleton code for this filter? 任何人都可以为此过滤器提供任何框架代码吗

You need to be able to capture the servlet's output in your filter. 您需要能够在过滤器中捕获servlet的输出。

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. 为此,您需要注入一个自定义的HttpServletResponseWrapper,它收集发送到getWriter().print()所有输出,以便您可以将其移交给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. 如果这是一个更大的项目,并且您可以更好地控制网络基础架构,那么在Java中不执行此操作也是一个好主意,但只需在Servlet容器前使用单独的代理服务器。 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). 您可以控制通常的缓存控制标头缓存的内容(如果servlet尚未使用过滤器,您可以使用过滤器进行设置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM