过滤器(Filter)是Servlet中常用的技术,可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,常用的场景有登录校验、权限控制、敏感词过滤等,下面介绍下Spring Boot配置过滤器的两种方式。

本文目录

一、@WebFilter注解方式二、@Bean注解方式三、查看运行效果

一、@WebFilter注解方式

使用@WebFilter注解为声明当前类为filter,第一个参数为该filter起一个名字,第二个参数为说明要拦截的请求地址,当前类需要实现Filter接口,里面有三个方法,分别为过滤器初始化、过滤方法和过滤器销毁。

@Slf4j
@WebFilter(filterName = "myFilter1", urlPatterns = "/*")
public class MyFilter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info(filterConfig.getFilterName() + " init");
    }     @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        log.info("myFilter1 begin");
        try {
            log.info("业务方法执行");
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("error!", e);
        }
        log.info("myFilter1 end");
    }     @Override
    public void destroy() {
    }
}

启动类添加@ServletComponentScan注解,@ServletComponentScan注解所扫描的包路径必须包含该Filter,代码如下:

@SpringBootApplication
@ServletComponentScan(basePackages = "com.example.demo.filter")
public class DemoApplication {     public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

二、@Bean注解方式

新建MyFilter2.java类,不要加注解@WebFilter,代码如下:

@Slf4j
public class MyFilter2 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info(filterConfig.getFilterName() + " init");
    }     @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        log.info("myFilter2 begin");
        try {
            log.info("业务方法执行");
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("error!", e);
        }
        log.info("myFilter2 end");
    }     @Override
    public void destroy() {
    }
}

新建配置类WebConfig.java,配置bean,代码如下:

@Configuration
public class WebConfig {     @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean(new MyFilter2());
        registration.addUrlPatterns("/test"); //
        registration.setName("myFilter2");
        return registration;
    }
}

三、查看运行效果

项目启动后浏览器访问http://localhost:8080/test,可以看到过滤器已生效,后台打印日志如下:

[nio-8080-exec-1] com.example.demo.filter.MyFilter1        : myFilter1 begin
[nio-8080-exec-1] com.example.demo.filter.MyFilter1        : 业务方法执行
[nio-8080-exec-1] com.example.demo.filter.MyFilter1        : myFilter1 end 

到此Spring Boot配置过滤器的两种方式已经全部实现,有问题欢迎留言沟通哦!
完整源码地址: https://github.com/suisui2019/springboot-study

推荐阅读

1.Spring Boot统一异常处理实战
2.从技术的角度分析下为什么不要在网上发“原图”
3.利用Spring Boot+zxing,生成二维码还能这么简单
4.Spring Boot之Profile--快速搞定多环境使用与切换
5.利用Spring Boot+WxJava实现网站集成微信登录功能


限时领取免费Java相关资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高并发分布式、大数据、机器学习等技术。
关注下方公众号即可免费领取:

Java碎碎念公众号

Spring Boot配置过滤器的两种方式的更多相关文章

  1. Spring Boot 整合 Shiro ,两种方式全总结!

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...

  2. spring boot 集成 Filter 的两种方式

    两种方式:(两种方式同时存在时,@Bean优先@ServletComponentScan实例化,生成两个对象) 1)@ServletComponentScan注解+@WebFilter注解 2)@Be ...

  3. spring boot 集成 Listener 的两种方式

    1)@ServletComponentScan注解+@WebListener注解 2)@Bean注解+ServletListenerRegistrationBean类

  4. spring boot返回Josn的两种方式

    1.Controller类上加@RestController注解 2.Controller类上加@Controller注解,Action接口上加@ResponseBody注解 @Responsebod ...

  5. spring配置属性的两种方式

    spring配置属性有两种方式,第一种方式通过context命名空间中的property-placeholder标签 <context:property-placeholder location ...

  6. Spring Boot 配置文件密码加密两种方案

    Spring Boot 配置文件密码加密两种方案 jasypt 加解密 jasypt 是一个简单易用的加解密Java库,可以快速集成到 Spring 项目中.可以快速集成到 Spring Boot 项 ...

  7. Spring集成Quartz框架的两种方式。

    可参考:https://blog.csdn.net/yk614294861/article/details/84324603 1.使用Spring与Quarta配置作业得两种方式: a.方式一,Met ...

  8. web.config文件中配置数据库连接的两种方式

    web.config文件中配置数据库连接的两种方式 标签: 数据库webconfig 2015-04-28 18:18 31590人阅读 评论(1)收藏举报    分类: 数据库(74)  在网站开发 ...

  9. MyBatis配置数据源的两种方式

    ---------------------siwuxie095                                     MyBatis 配置数据源的两种方式         1.配置方 ...

随机推荐

  1. 关于String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

    关于 String path = request.getContextPath(); String basePath = request.getScheme()+"://"+req ...

  2. 剑指Offer-44.翻转单词顺序列(C++/Java)

    题目: 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上.同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思.例如,“student. ...

  3. idea 出现Can't load AMD 64-bit .dll on a IA 32-bit platform错误

    这个错误是在说无法在IA 32位平台上加载AMD 64位.dll,解决方法如下 下载安装64位的jdk(方法和安装32位的一致,可百度查阅相关资料) 按如下步骤配置

  4. linux命令--查找与帮助

    一.搜寻命令 1.whereis命令 whereis是搜索系统命令的命令,也就是说,whereis 命令不能搜索普通文件, 而只能搜索系统命令. 命令名称:whereis 英文原意:locate th ...

  5. PAT 1005 Spell It Right 字符串处理

    Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output e ...

  6. H5 App实现热更新,不需要重新安装app

    直接上代码吧,你竟然搜到了我的文章就应该知道了,为什么要热更新 //app热更新下载 //假定字符串的每节数都在5位以下 function toNum(a) { //也可以这样写 var c=a.sp ...

  7. Format a Property Value 设置属性值的格式

    In this lesson, you will learn how to set a display format and an edit mask to a business class prop ...

  8. Linux 操作系统的权限为什么是1,2,4 而不是 1,2,3?如何用二进制来做权限管理

    1.二进制做权限的优点 大家都知道,在Linux操作系统中,x - 可执行权限,w - 可写权限 , r - 可读权限.其权限值分别是1,2,4,但是有没有想过为什么是1,2,4 而不是 1,2,3 ...

  9. Linux-正则、grep、sed学习笔记

    一.正则和grep 正则表达式的实现分成了两类: 基本正则表达式(BRE)和扩展的正则表达式(ERE). BRE 和 ERE 之间有什么区别呢?这是关于元字符的问题.BRE 可以辨别以下元字符: ^ ...

  10. 「SAP技术」已启用质检物料创建PO时候'STOCK TYPE'没有默认为X?

    「SAP技术」 SAP MM 已启用质检物料创建PO时候'STOCK TYPE'没有默认为X? Part I:SAP 标准行为 1, 物料11002335, QM视图里 01 inspection t ...