【Springboot】过滤器

Springboot实现过滤器

实现过滤器方式有两种:

  • Filter过滤器具体实现类
  • 通过@WebFilter 注解来配置

1、Filter过滤器具体实现类

1.1 实现Filter

@Component
@Slf4j
public class MyTestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("[ {} ] 创建啦...", this.getClass().getSimpleName());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("[ {} ] 执行啦...", this.getClass().getSimpleName());
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("[ {} ] 被摧毁啦...", this.getClass().getSimpleName());
    }
}

1.2 向spring容器注册filter

@Configuration
public class FilterConfig {

    @Resource
    private MyTestFilter myTestFilter;

    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(myTestFilter);
        registration.addUrlPatterns("/filter/*");
        registration.setName("myTestFilter");
        registration.setOrder(1);
        return registration;
    }
}

测试

2、通过@WebFilter 注解来配置

@Component
@WebFilter(urlPatterns = "/filter/*", filterName = "MyTestFilterByAnnotation")
@Slf4j
public class MyTestFilterByAnnotation  implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("注解 [ {} ] 创建啦...", this.getClass().getSimpleName());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("注解 [ {} ] 执行啦...", this.getClass().getSimpleName());
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("注解 [ {} ] 被摧毁啦...", this.getClass().getSimpleName());
    }
}

测试

本文作者:Hello、Lin

本文链接:https://www.cnblogs.com/HelloWxl/p/16618327.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Hello、Lin  阅读(235)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.