SpringBoot注册Servlet、Filter、Listener SpringBoot怎样注册Servlet、Filter、Listener的几种方式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot注册Servlet、Filter、Listener SpringBoot怎样注册Servlet、Filter、Listener的几种方式

技术小能手   2021-03-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 ServletListenerRegistrationBean<LoginSessionListener> regServletListener() {
    ServletListenerRegistrationBean<LoginSessionListener> loginSessionListener= new ServletListenerRegistrationBean<LoginSessionListener>();
    loginSessionListener.setListener(new LoginSessionListener());
    return loginSessionListener;

}

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们