Spring Boot (18) servlet、filter、listener

servlet、filter、listener,在spring boot中配置方式有两种:一种是以servlet3开始提供的注解方式,另一种是spring的注入方式。

servlet注解方式

  servlet3.0以前,servlet、filter、listener需要在web.xml中配置,从servlet3.0开始,支持通过类注解进行配置。在spring boot中如果要支持这种注解,必须在配置类增加一个@ServletComponentScan注解,来扫描servlet的注解

@ServletComponentScan
@SpringBootApplication

servlet注解配置,urlPatterns就是这个servlet请求路径,相当于spring mvc中的mapping 

https://www.cnblogs.com/baidawei/p/9001538.html

@WebServlet(urlPatterns = "/servlet")
public class myServlet extends HttpServlet {

}

filter注解,urlPatterns就是这个过滤器要过滤那些路径 

https://www.cnblogs.com/baidawei/p/9036783.html

@WebFilter("/*")
public class myFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    }

    @Override
    public void destroy() {

    }
}

listener注解配置,监听器就是全局性的,不需要配置路径 

https://www.cnblogs.com/baidawei/p/9035786.html

@WebListener
public class myListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

spring注入的方式

//servlet
    @Bean
    public ServletRegistrationBean myServlet(){
        //配置servlet及其请求的路径
        return new ServletRegistrationBean(new myServlet(),"/hello")
    }

    //过滤器
    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean myFilter = new FilterRegistrationBean();
        //配置过滤器
        myFilter.setFilter(new myFilter());
        //配置过滤器路径
        myFilter.addUrlPatterns("/*");
        return myFilter;
    }

    //监听器
    @Bean
    public ServletListenerRegistrationBean<myListener> myListener(){
        return new ServletListenerRegistrationBean<myListener>(new myListener());
    }

id命名冲突

  上面的spring注入方法都是用my*来命名,这个方法名就是spring中注入的bean的id,有一种习惯是用类名的首字母小写来命名id如:servletRegistrationBean等

如果项目中配置了druid监控,这个方法名已经被druid使用了,这个配置也将无法生效。这就是不使用spring boot默认组件可能会引发一些冲突问题,所以如非必要,优先使用spring boot默认的组件,稳定性和兼容性更高。

servlet注解还是spring注入?

  servlet注解不会有上面的冲突问题,而且简单易用。更主要的十servlet出自java官方的web技术,如tomcat之类的服务器,只知道有servlet二不知道spring为何物。所有对spring mvc控制层的请求,都是通过一个servlet也就是DispatchServlet进行分发的。请求首先到大servlet,分发以后才会到spring。如果不分发也就没有spring什么事了,spring需要依赖servlet才能处理请求。所以使用servlet注解才是原味的servlet。

猜你喜欢

转载自www.cnblogs.com/baidawei/p/9115432.html
今日推荐