其他分享
首页 > 其他分享> > 过滤器(Filter)

过滤器(Filter)

作者:互联网

过滤器(Filter)

Filter:用来过滤网站的数据

filter的用法和servlet基本一样

作用:

思路如图:

开发步骤:

  1. 导包
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.1</version>
  </dependency>
</dependencies>
  1. 编写过滤器(实现Filter接口,重写对应的方法)
public class CharacterEncodingFilter implements Filter {
    //初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化了");
    }
    /*
        1.过滤中的所有代码,再过滤特定请求的时候都会执行
        2.必须要让过滤器继续前进
            filterChain.doFilter(servletRequest,servletResponse);
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=UTF-8");

        System.out.println("CharacterEncodingFilter执行前");
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("CharacterEncodingFilter执行后");
    }
    //销毁
    @Override
    public void destroy() {
        System.out.println("CharacterEncodingFilter初始化了");
    }
}

重点:一定要写filterChain.doFilter(servletRequest,servletResponse);这样才可以让过滤器继续前进

  1. 在web.xml中配置
<servlet>
    <servlet-name>ShowServlet</servlet-name>
    <servlet-class>com.kuang.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ShowServlet</servlet-name>
    <url-pattern>/servlet/show</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <!--要过滤什么,路径包含什么就可以了-->
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>

这样改过滤的servlet就得到了过滤。

注意:这里的/一定不要把中间的/给丢掉,因为之前一直没注意这个/,导致在写路径时没有加/,结果运行tomcat一直报错,找了近半个小时错误没解决,最后发现是这个小问题!!!

标签:servlet,Filter,servletResponse,过滤器,servletRequest,CharacterEncodingFilter
来源: https://www.cnblogs.com/H-scholar/p/15760398.html