禁止浏览器缓存所有动态页面
有3 个HTTP 响应头字段都可以禁止浏览器缓存当前页面,它们在 Servlet 中的示例代码如下:
1 response.setDateHeader("Expires",-1); 2 response.setHeader("Cache-Control","no-cache"); 3 response.setHeader("Pragma","no-cache");
并不是所有的浏览器都能完全支持上面的三个响应头,因此最好是同时使用上面的三个响应头。
- Expires数据头:值为GMT时间值,为-1指浏览器不要缓存页面
- Cache-Control响应头有两个常用值:
- no-cache指浏览器不要缓存当前页面。
- max-age:xxx指浏览器缓存页面xxx秒。
1 package me.gacl.web.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 /** 15 * @ClassName: NoCacheFilter 16 * @Description: 禁止浏览器缓存所有动态页面 17 * @author: 孤傲苍狼 18 * @date: 2014-8-31 下午11:25:40 19 * 20 */ 21 public class NoCacheFilter implements Filter { 22 23 24 public void doFilter(ServletRequest req, ServletResponse resp, 25 FilterChain chain) throws IOException, ServletException { 26 //把ServletRequest强转成HttpServletRequest 27 HttpServletRequest request = (HttpServletRequest) req; 28 //把ServletResponse强转成HttpServletResponse 29 HttpServletResponse response = (HttpServletResponse) resp; 30 //禁止浏览器缓存所有动态页面 31 response.setDateHeader("Expires", -1); 32 response.setHeader("Cache-Control", "no-cache"); 33 response.setHeader("Pragma", "no-cache"); 34 35 chain.doFilter(request, response); 36 } 37 38 public void init(FilterConfig filterConfig) throws ServletException { 39 40 } 41 42 public void destroy() { 43 44 } 45 }
web.xml文件中的配置如下:
1 <filter> 2 <filter-name>NoCacheFilter</filter-name> 3 <filter-class>me.gacl.web.filter.NoCacheFilter</filter-class> 4 </filter> 5 6 <filter-mapping> 7 <filter-name>NoCacheFilter</filter-name> 8 <!--只拦截Jsp请求--> 9 <servlet-name>*.jsp</servlet-name> 10 </filter-mapping>
时间: 2024-10-18 18:26:21