解决浏览器缓存问题-过滤器方式

一、浏览器缓存机制:

解决浏览器缓存问题-过滤器方式_第1张图片

二、具体代码实现:

  • a、xml部分:

	
		EmsCacheCleanFilter
		com.snt.crm.web.filter.EmsCacheCleanFilter
	
	
		EmsCacheCleanFilter
		/*
	
  • b、filter过滤器部分:(方式一)
package com.snt.crm.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.snt.crm.common.utils.DateUtil;

/**
 * @description: 专门用于解决浏览器访问的缓存问题
 * @category 存在302问题
 * @date 2016年8月8日 下午2:09:02
 */
public class EmsCacheCleanFilter implements Filter{
	private static Logger log = LoggerFactory.getLogger(EmsCacheCleanFilter.class);
	private static final String STATIC_TAIL = "__xxxx_t=";
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		//1.获取request请求的url访问路径
		String reqeustURL = req.getRequestURL().toString();
		String queryStr = req.getQueryString();
		
		//2.通过给静态资源添加时间戳,去避免缓存问题
		//当访问的静态资源是以*.js,*.css,*.html结尾时才给其加上时间戳
		if(reqeustURL != null){
			if(checkURL(reqeustURL)){
				String newURL = null;
				//日期类型时间戳
				//String date = DateUtil.date2String(new Date(), "yyyyMMdd");
				//毫秒值风格时间戳
				String date = new Date().getTime()+"";
				//如果?后面有参数
				if(StringUtils.isNotBlank(queryStr) && queryStr.trim().indexOf(STATIC_TAIL)==-1){
					newURL = reqeustURL + "?" + queryStr + "&" + STATIC_TAIL + date;
					newURL = newURL.replaceAll("\\n\\r","");
					resp.setHeader("content-type", "text/application;charset=UTF-8");
					resp.sendRedirect(newURL);
					//request.getRequestDispatcher(newURL).forward(request, response);
					//return;
				}
				//如果?后面没有参数
				if(StringUtils.isBlank(queryStr)){
					newURL = reqeustURL + "?" + STATIC_TAIL + date;
					newURL = newURL.replaceAll("\\n\\r","");
					resp.setHeader("content-type", "text/application;charset=UTF-8");
					resp.sendRedirect(newURL);
					//request.getRequestDispatcher(newURL).forward(request, response);
				}
			}
			try {
				//只要请求url不为空放行
				chain.doFilter(request, response);
			} catch (Exception e) {
				log.info("[http请求出现异常,检查网络是否正常,或者再尝试一次!]--[zengwei]-[exception:]"+e);
			}
		}
	}
	
	/**
	 * @description:判断url中是否包含这些后缀名
	 * @param url 访问的url路径
	 * @return
	 */
	public Boolean checkURL(String url){
		String[] checks = {".js",".css",".html"};
		for (int i = 0; i < checks.length; i++) {
			if(url.endsWith(checks[i])){
				return true;
			}
		}
		return false;
	} 
	
	/**
	 * @description:解决302问题未解决)
	 * @param
	 * @param response
	 */
	public void fixResponse(HttpServletResponse response){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type", "text/application;charset=UTF-8");
		response.setStatus(200);
		try {
			PrintWriter out = response.getWriter();
			out.write(""
					+ "");
		} catch (IOException e) {
			log.info("[浏览器或系统出现异常,请重新访问]-[zengwei]");
		}
	}
	public void init(FilterConfig fConfig) throws ServletException {}
	public void destroy() {}
}
  • c.session级别的浏览器缓存控制(方式二)
public class LoginFilter implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        //log.info("request_uri=" + uri);
        if (uri.contains("logout") || uri.contains("/login") ||uri.contains("/page/token") || uri.contains("/home")
                || uri.contains("clearRedis") || uri.contains("/upload") || uri.contains("noAu") || uri.contains("/js")
                || uri.contains("/fonts") || uri.contains("/css") || uri.contains("/img") || uri.contains("/validate")) {
            if(uri.endsWith(".js") || uri.endsWith(".css")){
                String queryStr = httpServletRequest.getQueryString();
                if(!StringUtils.isEmpty(queryStr))
                    return true;
                String newURL = uri;
                HttpSession session = httpServletRequest.getSession();
                ServletContext sc = session.getServletContext();
                String staticVerKey = "staticVersion";
                String staticVer = (String)sc.getAttribute(staticVerKey);
                if(StringUtils.isEmpty(staticVer)){
                    staticVer = "_zhph_t="+(new Date().getTime());
                    sc.setAttribute(staticVerKey, staticVer);
                }
                newURL = newURL + "?" + staticVer ;
                httpServletResponse.sendRedirect(newURL);
                return false;
            }
            return true;
        }

        //  获取session  token 等
        HttpSession session = httpServletRequest.getSession();

        if (session.getAttribute("user") == null) {
            //根据请求方式,进行判断
            if (httpServletRequest.getMethod().equals("POST")) {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                Map map = new HashMap();
                map.put("resultCode", SystemConstant.NRC_FAIL);
                map.put("bizCode", SystemConstant.EBC_CODE_SESSION_INVALID);
                map.put("bizMsg", MessageUtils.getMessage(SystemConstant.EBC_CODE_SESSION_INVALID));
                map.put("data", "{}");
                httpServletResponse.getWriter().write(JSON.toJSONString(map));
            } else {
                log.info("[user_web]跳转到login页面!");
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/page/login");
            }
            return false;
        } else {
            /*session.setAttribute("user", session.getAttribute("user"));*/
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

学习Java的同学注意了!!! 
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:543120397 我们一起学Java!

你可能感兴趣的:(前端开发)