1. 程式人生 > >利用Java過濾器實現清理瀏覽器快取

利用Java過濾器實現清理瀏覽器快取

package cn.easted.edm.core.utils;

import java.io.IOException;

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;
/**
* @ClassName: NoCacheFilter
* @Description: 清除瀏覽器快取過濾器
* @author Wh
* @date 2017年6月5日 上午9:18:45
 */
public class NoCacheFilter implements Filter{

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
         HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            //禁止瀏覽器快取所有動態頁面
            response.setHeader("Pragma","no-cache");    
            response.setHeader("Cache-Control","no-cache");    
            response.setDateHeader("Expires", -1);   
            chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("----過濾器初始化----");
    }
    
    @Override
    public void destroy() {
         System.out.println("----過濾器銷燬----");
    }

}

web.xml中配置:

    <filter>
        <filter-name>NoCacheFilter</filter-name>
        <filter-class>cn.easted.edm.core.utils.NoCacheFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <!-- 排除統計干擾 -->
            <param-value>*.gif,*.jpg,*.png,*.css,*.ico</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>NoCacheFilter</filter-name>
         <url-pattern>/*</url-pattern>
    </filter-mapping>