<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");
}
}