当前位置: 代码迷 >> Web前端 >> 运用Filter控制缓存WebCache
  详细解决方案

运用Filter控制缓存WebCache

热度:140   发布时间:2012-10-09 10:21:45.0
使用Filter控制缓存WebCache

本文参考:http://www.the5fire.net/filter%E6%8E%A7%E5%88%B6%E7%BC%93%E5%AD%98webcache.html

首先建立一个WebCacheFilter.java来实现Filter:

package com.util;

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;
import javax.servlet.http.HttpSession;

public class WebCacheFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        //设定缓冲时间为5000秒
        res.setHeader("Cache-control", "max-age=5000");
       
        /*页面缓存设定
        * <br>确保浏览器不缓存页面数据
        res.setHeader("Cache-Control","no-cache");
        res.setHeader("Cache-Control","no-store");
        res.setDateHeader("Expires", 0);
        res.setHeader("Pragma","no-cache");
        */
       
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
       
    }

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

}

?然后配置web.xml文件,这里设定控制所有的gif文件和jpg文件。也就是从服务器端每隔5000秒才会发一次这种类型的文件过来(如果客户端进行请求的话):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <filter>
        <filter-name>SessionFilter</filter-name>
        <filter-class>com.util.SessionFilter</filter-class>
    </filter>
   
    <filter-mapping>
        <filter-name>SessionFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
   
    <filter-mapping>
        <filter-name>SessionFilter</filter-name>
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>
   
    <filter>
        <filter-name>WebCacheFilter</filter-name>
        <filter-class>com.util.WebCacheFilter</filter-class>
    </filter>
   
    <filter-mapping>
        <filter-name>WebCacheFilter</filter-name>
        <url-pattern>*.gif</url-pattern>
    </filter-mapping>
   
    <filter-mapping>
        <filter-name>WebCacheFilter</filter-name>
        <url-pattern>*.jpg</url-pattern>
    </filter-mapping>
</web-app>
?
  相关解决方案