禁用缓存案例

禁止浏览器缓存功能,使用的是响应协议头中的三个内容,如下:

Expires: -1

禁用浏览器缓存(考虑不同浏览器兼容性,存在三个字段)

Cache-Control: no-cache

Pragma: no-cache


在服务器端Servlet代码如下:

//设置响应头信息,禁止浏览器缓存.
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", -1);

但这种方式只能适用于一个JSP页面,而一个Web应用程序中可能包含多个JSP页面。如果想要整个Web应用程序的所有JSP页面都禁止缓存,需要使用过滤器功能来完成,具体操作如下:

Ø  创建一个过滤器类,实现Filter接口,并重写所有方法。

public class NoCacheFilter implements Filter {
	public void init(FilterConfig filterConfig) throws ServletException {}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//1 将ServletResponse强转为HttpServletResponse
		HttpServletResponse res = (HttpServletResponse)response;
		//2 禁止浏览器缓存功能
		res.setHeader("Cache-Control", "no-cache");
		res.setHeader("Pragma", "no-cache");
res.setDateHeader("Expires", -1);
		//3 过滤器放行
		chain.doFilter(request, response);
	}
	public void destroy() {}
}


Ø  配置Web工程中的web.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <filter>
  	<filter-name>NoCacheFilter</filter-name>
  	<filter-class>app.java.demo1.NoCacheFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>NoCacheFilter</filter-name>
  	<url-pattern>*.jsp</url-pattern>
  </filter-mapping>
</web-app>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值