jsp页面中静态文件的时间戳

在开发、调试js时,常常碰到firefox、chrome的缓存问题,有时候清空缓存还不生效,有时候还重启tomcat什么的,也麻烦。javascript

后来想到用时间戳来区别版本,可是,又不是每次全部的代码都要更新,每次访问都用系统的时间戳很差用,缓存就成摆设了。html

再后来,想到能够根据每一个js文件的修改时间来设置,其实对动态脚本一窍不通,由于页面的风格就是html+ajax,冠以jsp的后缀而已。最后用土办法解决了,代码大概就是下面的内容了,getTime.jsp。java

<%!
public long[] getTime(String basePath, String... files) {
	int size = files.length;
	long[] t = new long[size];
	for(int i = 0; i < size; i++) {
		t[i] = (new File(basePath + files[i])).lastModified();
	}
	return t;
}
%>

传入路径、须要获取时间戳的文件名,而后返回long类型的最后修改时间。页面代码大概以下:jquery

<%@page contentType="text/html;charset=UTF-8" language="java" import="java.io.File" errorPage=""%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<%@include file="getTime.jsp"%>
<%
String web_path=request.getContextPath();
String realPath = application.getRealPath("/");
long t[] = getTime(realPath, "/js/common.js", "/view/frame/js/main.js");
%>
<head>
	<!-- 省略 -->
</head>
<body>
	<!-- 省略 -->
	<script type="text/javascript" src="<%=web_path%>/js/jquery-1.8.3.min.js"></script>
	<script type="text/javascript" src="<%=web_path%>/js/common.js?v=<%=t[0]%>"></script>
	<script type="text/javascript">var web_path = '<%=web_path%>' || getContextPath();</script>
	<script type="text/javascript" src="<%=web_path%>/view/frame/js/main.js?v=<%=t[1]%>"></script>
</body>
</html>

最后在页面上能够看到时间戳了。web

不懂别人怎么作的。大笑暂时简单解决了问题,就是没放到项目中使用,纯属测试代码。ajax

相关文章
相关标签/搜索