spring boot 注入原生web组件

1.使用servlet API

  spring boot 注入原生web组件

 写Listener,filter,servlet的实现类,类上加对应注解

2.使用下面的方法

 spring boot 注入原生web组件

 写配置类

@Configuration
public class MyRegistConfig {

    @Bean
    public ServletRegistrationBean myServlet(){
        MyServlet myServlet = new MyServlet();

        return new ServletRegistrationBean(myServlet,"/my","/my02");
    }


    @Bean
    public FilterRegistrationBean myFilter(){

        MyFilter myFilter = new MyFilter();
//        return new FilterRegistrationBean(myFilter,myServlet());
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
        return filterRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
        MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
        return new ServletListenerRegistrationBean(mySwervletContextListener);
    }
}

扩展:为什么自定义的servlet比如urlpattern设置为/my的不会被spring的拦截器所拦截?

    因为容器中加载了两个servlet,dispatchservlet的urlpattern为/,自定义的servlet的urlpattern为/my.因此遵循精确有限原则,请求直接来到自定义的servlet中,因此不会被spring拦截器所拦截

上一篇:锱铢必较:在spring boot中使用神器防止CSRF***


下一篇:字符串截取