zoukankan      html  css  js  c++  java
  • JAVA入门[15]-过滤器filter

    一、过滤器

    过滤器是可用于 Servlet 编程的 Java 类,可以实现以下目的:

    • 在客户端的请求访问后端资源之前,拦截这些请求。
    • 在服务器的响应发送回客户端之前,处理这些响应。

    参考:http://www.journaldev.com/1933/java-servlet-filter-example-tutorial

    二、如何实现和配置过滤器

    1.定义过滤器

    过滤器实现接口: javax.servlet.Filter

    示例:定义过滤器实现计数器,counterFilter实现Filter接口

    public class counterFilter implements Filter {
        ServletContext context;
        int count;
        public void init(FilterConfig filterConfig) throws ServletException {
            context=filterConfig.getServletContext();
            String initCount=filterConfig.getInitParameter("count");
            count= Integer.valueOf(initCount);
        }
    
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            context.log("===counterFilter do Filter====");
            count++;
            context.setAttribute("count",count);
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        public void destroy() {
        }
    }
    

      

    jsp调用:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <div>欢迎,您是第 <%=application.getAttribute("count")%> 位访客</div>
    

      

    2.配置web.xml

    过滤器是可插拔的,通过web.xml来声明,然后映射到您的应用程序的部署描述符中的 Servlet 名称或 URL 模式。

    当 Web 容器启动 Web 应用程序时,它会为部署描述符中声明的每一个过滤器创建一个实例。

    web.xml 中的 filter-mapping 元素的顺序决定了 Web 容器应用过滤器到 Servlet 的顺序。若要反转过滤器的顺序,只需要在 web.xml 文件中反转 filter-mapping 元素即可。

    <filter>
        <filter-name>counterFilter</filter-name>
        <filter-class>filter.counterFilter</filter-class>
        <init-param>
            <param-name>count</param-name>
            <param-value>100</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>counterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

      

    3.如何给过滤器设置参数?

    在web.xml中用init-param节点设置参数,然后在 init 方法使用 FilterConfig 对象获取参数。

    context=filterConfig.getServletContext();
    String initCount=filterConfig.getInitParameter("count");
    

      

    三、使用注解@WebFilter定义过滤器

    @WebFilter注解可以实现了javax.servlet.Filter接口的类定义为过滤器组件

    @WebFilter(filterName = "filter1",initParams =@WebInitParam(name = "count",value = "100"),urlPatterns = "/*")
    public class filter1 implements Filter {
        ServletContext context;
        public void destroy() {
        }
    
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            context.log("filter1.doFilter()");
            chain.doFilter(req, resp);
        }
    
        public void init(FilterConfig config) throws ServletException {
            context=config.getServletContext();
        }
    }
    

      

    执行顺序:默认按照filter的名字排序,如果想调整顺序,还是要配置filter-mapping节点。

    <filter-mapping>
            <filter-name>filter2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <filter-mapping>
            <filter-name>filter1</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    

    查看一下Tomcat Localhost Log:

    02-Jun-2017 13:26:20.182 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
    02-Jun-2017 13:26:21.302 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'springmvc'
    02-Jun-2017 13:26:24.716 信息 [http-nio-8092-exec-1] org.apache.catalina.core.ApplicationContext.log ===counterFilter do Filter====
    02-Jun-2017 13:26:24.716 信息 [http-nio-8092-exec-1] org.apache.catalina.core.ApplicationContext.log filter2.doFilter()
    02-Jun-2017 13:26:24.716 信息 [http-nio-8092-exec-1] org.apache.catalina.core.ApplicationContext.log filter1.doFilter()

      

    四、一个应用场景:过滤器防止中文编码

    public class EncodeFilter implements Filter {
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request=(HttpServletRequest)servletRequest;
            HttpServletResponse response=(HttpServletResponse)servletResponse;
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            filterChain.doFilter(request,response);;
        }
    
        public void destroy() {
    
        }
    }
    
  • 相关阅读:
    EEPlat 的 后台业务处理模型
    poj 1012 Joseph (约瑟夫问题)
    python使用正則表達式
    二维码_encode与decode
    UITableView显示不全
    Bottle 中文文档
    不相交集python实现
    面试题1:落单的数
    Android开发/源代码资源汇总
    leetCode 26.Remove Duplicates from Sorted Array(删除数组反复点) 解题思路和方法
  • 原文地址:https://www.cnblogs.com/janes/p/6932306.html
Copyright © 2011-2022 走看看