Java基础、中级、高级、架构面试资料

Spring boot 自定义 Filter 教程

JAVA herman 4018浏览 0评论
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

使用过 Spring boot 后的程序员都对它赞不绝口,它作为 Java 开发的一个快速搭建项目的一个脚手架,能极大的方便我们创建项目,加快开发进度等。想要完全的学会 Spring boot,就要理解其中的原理,Spring boot 官方的文档写的也非常的详细。大家想要的各种功能,各种 API 说明,对接其它框架都有相应的文档和案例。所以需要深入的同学可以到 Spring boot 的官网看看它的一些使用教程。

有人在 QQ 里问我,Spring boot 如何自定义 Filter ?

其实很简单,Spring boot 对 Filter、Servlet、Listener 都是支持的。对应的它提供了三个强大的组件,分别是 FilterRegistrationBean、ServletRegistrationBean、ServletListenerRegistrationBean。其中 ServletRegistrationBean 我们在《Spring boot 添加 Servlet(ServletRegistrationBean) 支持的教程》这篇文章中介绍过,我这里就不在多少了。具体说说 FilterRegistrationBean。

@Configuration
public class XttblogConfig{
	@Bean
	public FilterRegistrationBean xttblogFilter(){
		//业余草:www.xttblog.com
		FilterRegistrationBean registrationBean = new FilterRegistrationBean();
		registrationBean.setFilter(new XttblogFilter());
		registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
		return registrationBean;
	}
	
	@Bean
	public FilterRegistrationBean myFilter(){
		//业余草:www.xttblog.com
		FilterRegistrationBean registrationBean = new FilterRegistrationBean();
		registrationBean.setFilter(new MyFilter());
		registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
		return registrationBean;
	}
}

想要自定义 Filter 就是这么简单,几行代码就搞定。多个 Filter 就配置多个 @Bean。

有些人说什么功能需要用到 Filter 啊,基本用不到吧。千万别这样想,既然 Spring boot 留了接口就一定有用到的场景,比如在使用阿里巴巴的数据库连接池 Druid 的时候等。所以说多学学还是很有必要的。

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » Spring boot 自定义 Filter 教程