Filter應用之2-設置某些頁面緩存或是不緩存

要想讓全部瀏覽器不緩存頁面,須要在每一個jsp上加上:瀏覽器

<%
          response.setHeader("expires","-1");
          response.setHeader("pragma","no-cache");
          response.setHeader("cache-control","no-cache");
      %>

測試,新建一個cache.jsp: 加上了上邊的三句話後,用IE查看緩存,沒有cache.jsp的緩存。可是每一個頁面都加這這代碼,有點麻煩,分析:能夠經過一個過慮器,對全部*.jsp過慮,設置三個頭,所有不緩存。這樣就不須要再每一個jsp頁面都寫上邊的三個頭了。緩存

第一步:實現過慮器接口服務器

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        //轉換
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("expires","-1"); 
          resp.setHeader("pragma","no-cache");
          resp.setHeader("cache-control","no-cache");
        //都放行
        chain.doFilter(request, response);
    }

第二步:配置過慮器,url-pattern=*.jspapp

<!-- 控制緩存的Filter -->
  <filter>
      <filter-name>cache</filter-name>
      <filter-class>com.lhy.filter.CacheFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>cache</filter-name>
      <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

第三步:設置對某些頁面緩存N天eclipse

@Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    //轉換
    HttpServletResponse resp = (HttpServletResponse)response;
    //設置頁面緩存時間
    //日曆
    Calendar c = Calendar.getInstance();
    //加2天
    c.add(Calendar.DATE,2);
    long time = c.getTimeInMillis();
    resp.setDateHeader("expires", time);
//    resp.setHeader("pragma","no-cache");
//    resp.setHeader("cache-control","no-cache");
    //都放行
    chain.doFilter(request, resp);
  }

注意:我用的myeclipse生成的jsp,head裏有這幾句話,若是是想要設置緩存幾天,必定要去掉,不然設置無效。jsp

<meta http-equiv="pragma" content="no-cache">:禁止瀏覽器從本地機的緩存中調閱頁面內容
<meta http-equiv="cache-control" content="no-cache">:指定請求和響應遵循的緩存機制
<meta http-equiv="expires" content="0"> :指定網頁在緩存中的過時時間,一旦網頁過時,必須到服務器上從新調閱。ide

相關文章
相關標籤/搜索