如何在整个servlet中禁用网页缓存 [英] how to disable web page cache throughout the servlets
问题描述
对于没有缓存的网页,在java控制器servlet中,我在一种方法中做了这样的事情:
To no-cache web page, in the java controller servlet, I did somthing like this in a method:
public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView(ViewConstants.MV_MAIN_HOME);
mav.addObject("testing", "Test this string");
mav.addObject(request);
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
return mav;
}
但这仅适用于特定的响应对象.我在Servlet中有许多类似的方法.而且我也有很多servlet.
But this only works for a particular response object. I have many similar methods in a servlet. And I have many servlets too.
如果我想在整个应用程序中禁用缓存,该怎么办?(我不想为每个响应对象添加以上代码).
If I want to disable cache throughout the application, what should I do? (I do not want to add above code for every single response object).
推荐答案
为什么不这样做通过过滤器?
过滤器是可以转换请求或响应的标头和内容(或两者)的对象.
A filter is an object that can transform the header and content (or both) of a request or response.
...
过滤器可以执行的主要任务如下:
The main tasks that a filter can perform are as follows:
...
- 修改响应头和数据.您可以通过提供响应的自定义版本来做到这一点.
只需注册您的Filter(实现Filter接口的类)并在 doFilter
方法.
Just register your Filter (class implementing the Filter interface) and modify your response within the doFilter
method.
编辑:例如
@WebFilter("/*")
public class NoCacheFilter implements javax.servlet.Filter {
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
请注意, @WebFilter
批注将需要Servlet 3.0,否则您可以通过 web.xml
进行注册.此路径"/*"将适用于您的应用程序的任何路径,但范围可能会缩小.
Note that the @WebFilter
annotation will require Servlet 3.0, otherwise you can register it via your web.xml
. This path of "/*", would apply to any path of your application, but could be narrowed in scope.
这篇关于如何在整个servlet中禁用网页缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!