SpringBoot如何注册Servlet、Filter、Listener的几种方式
作者:技术小能手 时间:2023-07-15 05:15:08
在Servlet 3.0之前都是使用web.xml文件进行配置,需要增加Servlet、Filter或者Listener都需要在web.xml增加相应的配置。Servlet 3.0之后可以使用注解进行配置Servlet、Filter或者Listener;springboot也提供了使用代码进行注册Servlet、Filter或者Listener。所以springboot有两种方式进行Servlet、Filter或者Listener配置。
方式一:使用注解
(1)注册Servlet
使用@WebServlet注册,需要在Servlet类上使用该注解即可,但是需要在@Configuration类中使用Spring Boot提供的注解@ServletComponentScan扫描注册相应的Servlet。
(2) 注册Filter
使用@WebFilter注册,需要在Filter类上使用该注解即可,但是需要在@Configuration类中使用Spring Boot提供的注解@ServletComponentScan扫描注册相应的Filter。
(3)注册Listener
使用@WebListener注册,需要在Filter类上使用该注解即可,但是需要在@Configuration类中使用Spring Boot提供的注解@ServletComponentScan扫描注册相应的Listener。
方式二:使用spring提供的方式
(1)注册Servlet
使用ServletRegistrationBean注册只需要在@Configuration类中加入类似以下的代码
@Bean
public ServletRegistrationBean regServlet() {
ServletRegistrationBean userServlet= new ServletRegistrationBean();
userServlet.addUrlMappings("/servlet");
userServlet.setServlet(new UserServlet());
return userServlet;
}
(2) 注册Filter
使用FilterRegistrationBean注册Filter,只需要在@Configuration类中加入类似以下的代码:
@Bean
public FilterRegistrationBean regFilter() {
FilterRegistrationBean userFilter = new FilterRegistrationBean();
userFilter .addUrlPatterns("/*");
userFilter .setFilter(new UserFilter ());
return userFilter ;
}
(3)注册Listener
使用ServletListenerRegistrationBean注册Listener只需要在@Configuration类中加入类似以下的代码:
@Bean
public ServletListenerRegistrationBean<LoginSessionListener> regServletListener() {
ServletListenerRegistrationBean<LoginSessionListener> loginSessionListener= new ServletListenerRegistrationBean<LoginSessionListener>();
loginSessionListener.setListener(new LoginSessionListener());
return loginSessionListener;
}
来源:https://yq.aliyun.com/articles/657775
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
c++野指针的原理以及避免方法
C#利用原图和水印图的重叠简单实现水印的方法
Java计算器核心算法代码实现
Java内存模型(JMM)及happens-before原理
![](https://img.aspxhome.com/file/2023/2/59972_0s.png)
相对路径和绝对路径的写法总结
Java裁剪压缩PNG图片,透明背景色变黑的解决方案
Java中this和super的区别及this能否调用到父类使用
![](https://img.aspxhome.com/file/2023/6/61876_0s.webp)
使用idea和gradle编译spring5源码的方法步骤
![](https://img.aspxhome.com/file/2023/9/84219_0s.jpg)
Java开发之Lombok指南
![](https://img.aspxhome.com/file/2023/2/64202_0s.jpg)
Android实现双层ViewPager嵌套
![](https://img.aspxhome.com/file/2023/4/96804_0s.gif)
Java 梳理总结关于static关键字常见问题
Android控件之TabHost用法实例分析
![](https://img.aspxhome.com/file/2023/9/122129_0s.png)
利用HorizontalScrollView实现滑动页面时的缩放效果
![](https://img.aspxhome.com/file/2023/3/88113_0s.gif)
@RequestBody,@RequestParam和@Param的区别说明
![](https://img.aspxhome.com/file/2023/2/72302_0s.png)
为spring get请求添加自定义的参数处理操作(如下划线转驼峰)
SpringBoot整合liquibase及liquibase生成初始化脚本的方式
![](https://img.aspxhome.com/file/2023/9/91089_0s.png)
Spring集成Swagger常见错误及解决办法
![](https://img.aspxhome.com/file/2023/9/88749_0s.png)