利用 filter 机制 给 静态资源 url 加上时间戳,来防止js和css文件的缓存,利于开发调试...

本文介绍了一种通过在静态资源请求中加入时间戳来避免浏览器缓存的方法。具体实现是在请求URL后添加特定参数并附带当前时间的时间戳。

直接上代码:

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);
				return;
			}
			if(StringUtils.isBlank(queryStr)){
				newURL = requestURL + "?" + ParameterConfig.STATIC_TAIL + new Date().getTime();
				resp.sendRedirect(newURL);
				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=";

  

配置下过滤器就行了,chrome 调试的 效果如下,可以看到  chrome浏览器在获取css和js文件时,路径上携带了时间戳:

在开发阶段还是比较有用的。

转载于:https://www.cnblogs.com/digdeep/p/5539131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值