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

标签:SpringBoot,注册,Servlet,Filter,Listener
0
投稿

猜你喜欢

  • c++野指针的原理以及避免方法

    2023-10-07 09:18:53
  • C#利用原图和水印图的重叠简单实现水印的方法

    2023-04-21 01:41:24
  • Java计算器核心算法代码实现

    2022-03-18 05:38:55
  • Java内存模型(JMM)及happens-before原理

    2023-11-25 00:41:05
  • 相对路径和绝对路径的写法总结

    2022-06-17 07:38:47
  • Java裁剪压缩PNG图片,透明背景色变黑的解决方案

    2023-11-25 13:21:27
  • Java中this和super的区别及this能否调用到父类使用

    2023-01-05 12:03:13
  • 使用idea和gradle编译spring5源码的方法步骤

    2022-04-02 12:21:53
  • Java开发之Lombok指南

    2022-11-19 21:49:28
  • Android实现双层ViewPager嵌套

    2021-12-23 02:35:52
  • Java 梳理总结关于static关键字常见问题

    2021-12-11 11:49:01
  • Android控件之TabHost用法实例分析

    2021-07-19 10:35:21
  • 利用HorizontalScrollView实现滑动页面时的缩放效果

    2022-12-09 13:22:32
  • @RequestBody,@RequestParam和@Param的区别说明

    2023-07-20 06:29:03
  • 为spring get请求添加自定义的参数处理操作(如下划线转驼峰)

    2021-12-04 13:01:43
  • SpringBoot整合liquibase及liquibase生成初始化脚本的方式

    2023-07-29 11:53:18
  • Spring集成Swagger常见错误及解决办法

    2023-07-10 05:01:17
  • Java中Map的遍历方法及性能测试

    2023-07-14 08:54:15
  • C语言安全编码之数组索引位的合法范围

    2021-12-08 06:09:51
  • Java面向对象基础知识之委托和lambda

    2022-07-28 16:51:11
  • asp之家 软件编程 m.aspxhome.com