HTTP/1.1 Cache-Control的理解

来源:百度文库 编辑:神马文学网 时间:2024/04/29 06:55:30
网页的缓存是由HTTP消息头中的“Cache-control”来控制的,常见的取值有private、no-cache、max-age、must-revalidate等,默认为private。其作用根据不同的重新浏览方式分为以下几种情况:
(1) 打开新窗口
如果指定cache-control的值为private、no-cache、must-revalidate,那么打开新窗口访问时都会重新访问服务器。而如果指定了max-age值,那么在此值内的时间里就不会重新访问服务器,例如:
Cache-control: max-age=5
表示当访问此网页后的5秒内再次访问不会去服务器
(2) 在地址栏回车
如果值为private或must-revalidate(和网上说的不一样),则只有第一次访问时会访问服务器,以后就不再访问。如果值为no-cache,那么每次都会访问。如果值为max-age,则在过期之前不会重复访问。
(3) 按后退按扭
如果值为private、must-revalidate、max-age,则不会重访问,而如果为no-cache,则每次都重复访问
(4) 按刷新按扭
无论为何值,都会重复访问


项目中使用过滤器来设置网页的缓存
FilterConfig fc; 

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        // set the provided HTTP response parameters
        for (Enumeration e = fc.getInitParameterNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            response.addHeader(headerName, fc.getInitParameter(headerName));
        }
        // pass the request/response on
        chain.doFilter(req, response);
    } 
配置文件的配置:

        NoCache
        filter.CacheFilter
        
            Cache-Control
            no-cache, must-revalidate
        

    

    
        CacheForWeek
        filter.CacheFilter
        
            Cache-Control
            max-age=604800
        

    


    
        CacheForWeek
        *.js
    

    
        CacheForWeek
        *.css
    
 
    
        CacheForWeek
        *.gif
    
 
上述设置保存了1周的缓存。