最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
SpringBoot如何注册Servlet、Filter、Listener的几种方式
时间:2018-10-30 编辑:猪哥 来源:一聚教程网
在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 ServletListenerRegistrationBeanregServletListener() { ServletListenerRegistrationBean loginSessionListener= new ServletListenerRegistrationBean (); loginSessionListener.setListener(new LoginSessionListener()); return loginSessionListener; }
相关文章
- SpringBoot自定义bean绑定解析 10-24
- Javaweb工程运行报错HTTP Status 404解决教程 10-20
- JAVA获取jvm和操作系统相关信息方法 10-20
- BeanFactory和FactoryBean的区别讲解 10-20
- 微信小程序的宿主环境实现教程 10-10
- dispatchEvent解决重叠元素响应事件教程 10-10