浏览器缓存问题--时间戳

本文介绍使用时间戳解决浏览器缓存问题。

在IE或者其他的很多浏览器中,如果你每次请求的地址是相同的,浏览器就不会去连接服务器而是去读取缓存,这样对于很多应用来时是非常好的,可以降低服务器的压力或者减少带宽的使用,但是对于ajax应用,很多都是必须保持时时的连接与服务器进行交互,所以需要使用一个小技巧,时间戳来使每次的请求地址都不同,从而跳过浏览器的缓存 机制实现每次的请求服务器,这样的功能在图片验证码的时候也是比较常用的一种方法。

下面提供三种方法:

利用 filter 机制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class WeiXinFilter implements Filter {

private static Logger logger = LoggerFactory.getLogger(WeiXinFilter.class);

public void init(FilterConfig fConfig) throws ServletException {
}

public void destroy() {
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String requestURL = req.getRequestURL().toString();
String queryStr = req.getQueryString();

// add timestamp to static resource, to avoid cache
if (requestURL \!=null && (requestURL.endsWith(".js") \|\|requestURL.endsWith(".css"))){ // static resource
String newURL = null;
if (StringUtils.isNotBlank(queryStr) && queryStr.trim().indexOf(ParameterConfig.STATIC_TAIL) == \-1){
newURL = requestURL + "?" + queryStr + "&" + ParameterConfig.STATIC_TAIL + new Date().getTime();
resp.sendRedirect(newURL);
// req.getRequestDispatcher(newURL).forward(request, response);
return;
}
if (StringUtils.isBlank(queryStr)) {
newURL = requestURL + "?" + ParameterConfig.STATIC_TAIL + new Date().getTime();
resp.sendRedirect(newURL);
// req.getRequestDispatcher(newURL).forward(request, response);
return;
}
try {
chain.doFilter(request, response);
} catch (Exception e) {
logger.error(e.toString());
}
return;
}
}
}

public class ParameterConfig {
/* \* 静态资源 为防止缓存,加上时间戳标志 \ */
public static final String STATIC_TAIL = "__oawx_t=";
}

利用JS脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script type="text/javascript">
function test(){
//1.获取文本框中的值
var value = $("#userName").val();
//2.将文本框中的内容发送给后台服务器
var url = "/Ajax/servlet/AjaxServlet?name="+value;
url = convertURL(url);
alert(url);
$.get(url,null,callback);
}
//给url地址增加时间戳,骗过浏览器,不读去缓存
function convertURL(url){
var timestmp = (new Date()).valueOf();
//将时间戳追加到url上面
url = url+ "&t=" +timestmp;
return url;
}

function callback(data){//回调函数
//3.接受服务器的返回的数据
//alert(data);
//4.将结果显示在页面中
$("#div1").html(data);
}
</script>

html页面设置

1
2
3
4
5
<meta http-equiv="X-UA-Compatible" content="IE=8">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Cache" content="no-cache">
坚持原创技术分享,您的支持将鼓励我继续创作!
分享到: