首页 > 学院 > 开发设计 > 正文

通过Filter设置HTTP hander中的cache-control

2019-11-06 08:49:59
字体:
来源:转载
供稿:网友
  <filter>  	<filter-name>cache-control</filter-name>  	<filter-class>com.hibtest6.filter.CacheControl</filter-class>  	<init-param>  		<param-name>.CSS</param-name>  		<param-value>520</param-value>  	</init-param>  	<init-param>  		<param-name>.gif</param-name>  		<param-value>520</param-value>  	</init-param>  	<init-param>  		<param-name>.js</param-name>  		<param-value>520</param-value>  	</init-param>  </filter>  <filter-mapping>  	<filter-name>cache-control</filter-name>  	<url-pattern>*.css</url-pattern>  </filter-mapping>  <filter-mapping>  	<filter-name>cache-control</filter-name>  	<url-pattern>*.gif</url-pattern>  </filter-mapping>  <filter-mapping>  	<filter-name>cache-control</filter-name>  	<url-pattern>*.js</url-pattern>  </filter-mapping>
public class CacheControl implements Filter{	PRivate Map map = new HashMap<String, Long>();		public void destroy() {		System.out.println("destroy");	}	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {		HttpServletRequest httpServletRequest = (HttpServletRequest) request;		String requestUri = httpServletRequest.getRequestURI();//SSH2/js/easyui.css				String cache = httpServletRequest.getHeader("cache-Control");		if(requestUri.lastIndexOf(".")!=-1){			String str = requestUri.substring(requestUri.lastIndexOf(".") , requestUri.length());			Long strValue = (Long) map.get(str);			if(strValue!=null){				HttpServletResponse httpServletResponse = (HttpServletResponse) response;				httpServletResponse.setHeader("Cache-Control", "max-age="+strValue);				httpServletResponse.setDateHeader("Expires", System.currentTimeMillis()+strValue*1000);				response = httpServletResponse;			}		}		chain.doFilter(request, response);	}	public void init(FilterConfig filterConfig) throws ServletException {		Enumeration enumeration = filterConfig.getInitParameterNames();		while(enumeration.hasMoreElements()){			String eleName = (String) enumeration.nextElement();			if(eleName==null || eleName==""){				continue;			}			String eleValue = filterConfig.getInitParameter(eleName);			Long eleValueLong = Long.parseLong(eleValue); 			if(eleValueLong>0){				map.put(eleName, eleValueLong);			}		}		System.out.println(map);		System.out.println("init");	}}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表