1. 程式人生 > >使用Filter 過濾器實現禁用快取

使用Filter 過濾器實現禁用快取

對比:設定一個有快取的 filter

設定一個可以快取的 過濾器, 對於一些靜態包含的 css  圖片, js 等檔案 比較適合

 一  .建立  實現filter  介面的 實現類

package filter;

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;

public class CatchFilter implements Filter {

	private FilterConfig filterConfig;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		//把請求的res req   造型 為 HttpServletResponse,HttpServletRequest
		HttpServletResponse response=(HttpServletResponse) res;
		HttpServletRequest request=(HttpServletRequest) req;
		
		// 獲取請求的url
		String uri=request.getRequestURI();
		String suffix=uri.substring(uri.lastIndexOf(".")+1);
		// 獲取字尾名 設定快取的時間
		if("css".equalsIgnoreCase(suffix)){
			String cssDate=filterConfig.getInitParameter("css");
			response.setDateHeader("Expires", System.currentTimeMillis()+Integer.valueOf(cssDate)*1000);
			System.out.println("---------------css------------");
		}else if("jpg".equalsIgnoreCase(suffix)){
			String jpgDate=filterConfig.getInitParameter("jpg");
			response.setDateHeader("Expires", System.currentTimeMillis()+Integer.valueOf(jpgDate)*1000);
			System.out.println("---------------jpg------------");
			
		}else if("js".equalsIgnoreCase(suffix)){
			String jsDate=filterConfig.getInitParameter("js");
			response.setDateHeader("Expires", System.currentTimeMillis()+Integer.valueOf(jsDate)*1000);
			System.out.println("---------------js------------");
		}
		
		chain.doFilter(request, response);
		
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig=filterConfig;
	}

}