• 欢迎光临~

Springboot项目如何创建Filter

开发技术 开发技术 2022-09-28 次浏览
方式一:使用@WebFilter+@ServletComponentScan

1)创建类com.zhi.demo.filter.CustomFilter1,添加注解@WebFilter(urlPatterns = { "/test1/*" }),urlPatterns表示需要过滤的地址

@WebFilter(urlPatterns = { "/test1/*" })
public class CustomFilter1 implements Filter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        logger.info("请求{}经过过滤器", httpServletRequest.getRequestURI());
        chain.doFilter(request, response);
    }
}

2)在启动类上添加注解@ServletComponentScan(basePackages = "com.zhi.demo.filter")

@ServletComponentScan(basePackages = "com.zhi.demo.filter")
@SpringBootApplication
public class InterceptApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder(InterceptApplication.class).bannerMode(Mode.OFF).run(args);
    }
}

方式二:使用FilterRegistrationBean注册拦截器

1)创建类com.zhi.demo.filter.CustomFilter2

public class CustomFilter2 implements Filter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        logger.info("请求{}经过过滤器", httpServletRequest.getRequestURI());
        chain.doFilter(request, response);
    }
}

2)使用FilterRegistrationBean载入过滤器,并只对/test2/*进行拦截

@Configuration
public class BeanConfig {
    @Bean
    public FilterRegistrationBean<CustomFilter2> filterRegistrationBean() {
        FilterRegistrationBean<CustomFilter2> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CustomFilter2());
        registration.addUrlPatterns("/test2/*");
        return registration;
    }
}

 

注意:

1、使用@Component注解时,也可以将Filter注册到容器中,但@WebFilter配置信息会失效

2、同时使用上面的2种方式,会两次拦截

 

程序员灯塔
转载请注明原文链接:Springboot项目如何创建Filter
喜欢 (0)