zoukankan      html  css  js  c++  java
  • Filter过滤器

    定义:
    FilterConfig对象提供对servlet环境及web.xml文件中指派的过滤器名的访问。
    FilterConfig对象具有一个getInitParameter方法,它能够访问部署描述符文件(web.xml)中分配的过滤器初始化参数。

    实例:
    将下面的代码加入到web.xml中,试用FilterConfig就可以获得以 filter 作为描述标签内的参数。

    <!-- The Cache Filter -->
    <filter>
    <!-- 设计过滤处理类,生成静态页面 -->
    <filter-name>CacheFilter</filter-name>
    <filter-class>com.jspbook.CacheFilter</filter-class>

    <!-- 不需要缓存的URL -->
    <init-param>
    <param-name>/TimeMonger.jsp</param-name>
    <param-value>nocache</param-value>
    </init-param>

    <init-param>
    <param-name>/TestCache.jsp</param-name>
    <param-value>nocache</param-value>
    </init-param>

    <!-- 缓存超时时间, 单位为秒 -->
    <init-param>
    <param-name>cacheTimeout</param-name>
    <param-value>600</param-value>
    </init-param>

    <!-- 是否根据浏览器不同的地区设置进行缓存(生成的缓存文件为 test.jspid=1_zh_CN 的格式) -->
    <init-param>
    <param-name>locale-sensitive</param-name>
    <param-value>true</param-value>
    </init-param>

    </filter>

    <filter-mapping>
    <filter-name>CacheFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
    </filter-mapping> 

    用法:

    filterConfig.getInitParameter("locale-sensitive"); 得到的就是 ture
    filterConfig.getInitParameter("cacheTimeout"); 得到的就是 600
    filterConfig.getInitParameter(request.getRequestURI()); 得到的就是param-name 对应的 param-value 值


    过滤处理类:

    public class CacheFilter implements Filter {
    ServletContext sc;
    FilterConfig fc;
    long cacheTimeout = Long.MAX_VALUE;

    public void doFilter(ServletRequest req, ServletResponse res,
    FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    // check if was a resource that shouldn't be cached.
    String r = sc.getRealPath("");
    String path = fc.getInitParameter(request.getRequestURI());
    if (path != null && path.equals("nocache")) {
    chain.doFilter(request, response);
    return;
    }
    path = r + path;

    }

    public void init(FilterConfig filterConfig) {
    this.fc = filterConfig;
    String ct = fc.getInitParameter("cacheTimeout");
    if (ct != null) {
    cacheTimeout = 60 * 1000 * Long.parseLong(ct);
    }
    this.sc = filterConfig.getServletContext();
    }

    public void destroy() {
    this.sc = null;
    this.fc = null;
    }
    }

  • 相关阅读:
    Android 亮度调节
    Android异步回调中的UI同步性问题
    Java总结篇系列:Java 反射
    Node入门教程(4)第三章:第一个 Nodejs 程序
    Node入门教程(3)第二章: Node 安装
    Node入门教程(2)第一章:NodeJS 概述
    Node入门教程(1)目录
    前端面试题:JS中的let和var的区别
    IT学习逆袭的新模式,全栈实习生,不8000就业不还实习费
    11-移动端开发教程-zepto.js入门教程
  • 原文地址:https://www.cnblogs.com/jietz0407-com/p/6196478.html
Copyright © 2011-2022 走看看