JavaWeb中的filter简单实现

  1. 定义一个类,实现接口Filter
  2. 复写方法
  3. 配置拦截路径
    1. web.xml
    2. 注解

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

//@WebFilter("/*")
public class FilterDemo1 implements Filter {
    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("via filter1...");
        //放行操作
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}


web.xml的配置

    <filter>
        <filter-name>demo1</filter-name>
        <filter-class>com.code_g.filter.FilterDemo1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>demo1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

posted @ 2021-05-11 21:37  code-G  阅读(101)  评论(0编辑  收藏  举报