您现在的位置是:首页 > 文章详情

SpringBoot如何注册Servlet、Filter、Listener

日期:2018-10-25点击:343

在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; }

本文作者: java乐园

本文来自云栖社区合作伙伴“JAVA乐园”,了解相关信息可以关注“JAVA乐园


原文链接:https://yq.aliyun.com/articles/657775
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章