Filter的创建和使用以及基础知识

    xiaoxiao2021-03-25  132

    Filter的创建和基本用法: 1、cd src,新建com.filter包,新建TestFilter类,实现servlet下的Filter接口 2、实现doFilter函数。     @Override     publicvoiddoFilter(ServletRequestrequest, ServletResponseresponse,            FilterChainchain)throwsIOException, ServletException {        //要过滤的信息        if(request.getParameter("username").equals("a")){            System.out.println("yes");        }else{            System.out.println("no");        }        //开始过滤        chain.doFilter(request,response);     } 3、配置web.xml     <filter>        <filter-name>TestFilter</filter-name>        <filter-class>com.filter.TestFilter</filter-class>     </filter>     <filter-mapping>        <filter-name>TestFilter</filter-name>        <!--配置哪些文件需要被过滤,"/*"表示所有文件-->        <url-pattern>/*</url-pattern>     </filter-mapping> 4、新建jsp测试文件,如:filter.jsp,并在浏览器中访问filter.jsp进行测试 Filter通过web.xml和init函数传递配置信息: 1、修改web.xml中的<filter>标签     <filter>        <filter-name>TestFilter</filter-name>        <filter-class>com.filter.TestFilter</filter-class>        <init-param>            <param-name>username</param-name>            <param-value>a</param-value>        </init-param>     </filter> 2、TestFilter中创建一个成员变量,用来存储配置信息:     privateStringuname; 3、实现init函数,获取配置文件web.xml中的init-param信息:     @Override     publicvoidinit(FilterConfigconfig)throwsServletException {        //获取配置文件web.xml中的init-param信息        Stringusername=config.getInitParameter("username");        //处理init-param为空的情况        if(username==null||username.trim().equals("")){            uname="a";        }else{            uname=username;        }     } 4、修改doFilter函数,把”a”用uname替换掉     @Override     publicvoiddoFilter(ServletRequestrequest, ServletResponseresponse,            FilterChainchain)throwsIOException, ServletException {        //要过滤的信息        if(request.getParameter("username").equals(uname)){            System.out.println("yes");        }else{            System.out.println("no");        }        //开始过滤        chain.doFilter(request,response);     }
    转载请注明原文地址: https://ju.6miu.com/read-8132.html

    最新回复(0)