本文共 2245 字,大约阅读时间需要 7 分钟。
当访问一个web资源时,没有得到对应的结果,有可能是Filter没有放行资源
静态资源和动态资源进行不同的缓存处理,代码如下:====NO2判段是否以jsp结尾 处Expires数据头:值为GMT时间值,为-1指浏览器不要缓存页面Cache-Control响应头有两个常用值: no-cache指浏览器不要缓存当前页面。max-age:xxx指浏览器缓存页面xxx秒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;//禁止浏览器缓存动态资源,例如JSP资源public class FilterDemo5 implements Filter { //思路 private FilterConfig filterConfig; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException { //NO将父子接口强转 HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; //NO1取得客户端访问的资源的URI,形式/day04/login.jsp //http: String uri = request.getRequestURI(); //静态资源和动态资源进行不同的缓存处理,代码如下: //NO2判段是否以jsp结尾,即动态资源 if(uri!=null && uri.endsWith("jsp")){ //NO3如果是动态资源,设置三个响应头通知浏览器不缓存 response.setHeader("expires","-1"); response.setHeader("cache-control","no-cache"); response.setHeader("pragma","no-cache"); }else if(uri!=null && uri.endsWith("html")){ //NO4如果是静态资源,缓存一定的时间 String strHtml = filterConfig.getInitParameter("html"); long time = System.currentTimeMillis()+Integer.parseInt(strHtml)*1000; //time为毫秒值 response.setDateHeader("expires",time); response.setHeader("cache-control",time/1000+""); response.setHeader("pragma",time/1000+""); } //NO5放行资源 chain.doFilter(request,response); } public void destroy() { }}
web.xml
FilterDemo5 cn.itcast.web.filter.FilterDemo5 html 86400 FilterDemo5 /*
转载于:https://blog.51cto.com/357712148/2105116