用于缓存的Servlet过滤器 [英] Servlet filter for caching
问题描述
我正在为缓存创建一个servlet过滤器。想法是将响应主体缓存到memcached。响应体由(结果是字符串)生成:
response.getWriter()。print(result);
我的问题是,由于响应正文将被放入memcached而不做修改,我还能需要创建一个自定义的HttpServletResponseWrapper?任何人都可以为此过滤器提供任何框架代码吗?
您需要能够在过滤器中捕获servlet的输出。 / p>
为此,您需要注入一个自定义的HttpServletResponseWrapper,它收集发送到 getWriter()的所有输出.print()
在某个地方,你可以把它交给memcached。
也许是这样的:
ByteArrayOutputStream baos = new ByteArrayOutputStream(3000);
final PrintWriter w = new PrintWriter(new OutputStreamWriter(baos,UTF-8));
HttpServletResponse wrapper = new HttpServletResponseWrapper(response){
@Override
public PrintWriter getWriter()抛出IOException {
return w;
}
};
如果这是一个更大的项目,你可以更好地控制网络基础设施,它也可能是一个最好不要在Java中执行此操作,而只需在Servlet容器前使用单独的代理服务器。您可以控制通常的缓存控制标头缓存的内容(如果servlet尚未使用过滤器,您可以使用过滤器进行设置)。
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?
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).
这篇关于用于缓存的Servlet过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!