利用 filter 機制 給 靜態資源 url 加上時間戳,來防止js和css文件的緩存,利於開發調試

直接上代碼:css

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文件時,路徑上攜帶了時間戳:java

在開發階段仍是比較有用的。chrome

相關文章
相關標籤/搜索