过滤器(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. 网易发起“疾风”智造IoT联盟,深化“互联网+先进制造业”发展

    7月26日,2019网易云创峰会在杭州拉开序幕,本次峰会以“连接•洞察•进化”为主题,汇聚行业领袖.技术大咖及业界代表,探讨技术演进与行业应用趋势,研商生态合作升级.共赢未来的道路.上午的主论坛中,网 ...

  2. jQuery-跨域问题的处理

    调用登录接口时,后端一般会在调用登录接口成功后,在response中设置cookie,之后前端的每次请求都会自动地在请求头上加上后端设置好的cookie,这对前端来说是透明的. 当登录接口与登录后调用 ...

  3. C语言中的顺序点

    C语言盲点1.函数参数的求值顺序依赖于编译器,例如f(a,a++);是先求a++还是求a不一定 2.C语言中的大多数运算符对其操作数的求值顺序也依赖于编译器 警告int i = f() * g();这 ...

  4. App 自动化框架设计思路

    最近在整理和学习Appium+Java 自动化框架,对APP自动化框架的部分设想参考了一些文章,先进行整理下: 框架的思路一: 思考引入:https://www.cnblogs.com/yunfeio ...

  5. Cypress 之 URL访问

    visit 作用: 访问一个远程URL. (建议:使用前设置 baseUrl) 语法: cy.visit(url) cy.visit(url, options) cy.visit(options) 使 ...

  6. ASP.NET MVC教程四:ASP.NET MVC中页面传值的几种方式

    准备 在Models文件夹里面新添加Student实体类,用来模拟从Controller向View传递数据,Student类定义如下: using System; using System.Colle ...

  7. C#中类的修饰符

    Q&A  项目=程序集=assembly 1,Q:类的修饰符有哪些? A:   有 new.public.protect.internal.private.abstract.sealed.st ...

  8. Sql sever DateDiff 函数

    函数: DATEDIFF(datepart,startdate,enddate) 具体实例: --相差年数 结果0 SELECT DATEDIFF(yy,'2008-12-29','2008-12-1 ...

  9. Redis报错:ERR This instance has cluster support disabled

    异常分析从报错误的信息ERR This instance has cluster support disabled很明显看得出来,是没有启动redis集群功能,可是我项目配置的集群的配置方式,要么修改 ...

  10. automaticallyAdjustsScrollViewInsets

    参考链接: https://www.jianshu.com/p/a1987a7c11ba