Spring Boot配置Servlet、Filter、Listener

Spring Boot集成了servlet容器,当我们在pom文件中增加spring-boot-starter-web的maven依赖时,不做任何web相关的配置便能提供web服务,这还得归于spring boot 自动配置的功能(因为加了*****EnableAutoConfiguration*****的注解),帮我们创建了一堆默认的配置,以前在web.xml中配置,现在都可 以通过spring bean的方式进行配置,由spring来进行生命周期的管理,大多数情况下,我们需要重载这些配置(例如修改服务的启动端 口,contextpath,filter,listener,servlet,session超时时间等)

在SpringBoot中如何配置Servelt、Filter、Listener

大家可能已经注意到,在SpringBoot中,不光将Spring的配置文件省略了,连web容器的web.xml文件都省略了,而之前,我们通常都是将ServeltFilterListener等配置在web.xml中配置的,而SpringBoot提供了更加简化的配置。 在说如何配置之前,我们先将演示用ServeltFilterListener的准备好。

Filter

public class DemoFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("demo filter...");
        chain.doFilter(request, response);
    }
}

Servlet

public class DemoServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("demo servlet...");
        resp.getWriter().write("demo servlet...");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

Listener

public class DemoListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("demo listener...");
    }
}

在准备好这些文件之后,我们开始配置。SpringBoot提供了2种方式配置Servlet、Listener、Filter。一种是基于RegistrationBean,另一种是基于注解。

1.基于RegistrationBean

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public FilterRegistrationBean<DemoFilter> getDemoFilter() {
        FilterRegistrationBean<DemoFilter> bean = new FilterRegistrationBean<>();
        //List<String> urlPatterns = new ArrayList<>();
        //urlPatterns.add("/*");
        bean.setFilter(new DemoFilter());
        bean.addUrlPatterns("/*");
        bean.setOrder(1);
        bean.setName("myFilter");
        return bean;
    }

    @Bean
    public ServletRegistrationBean<DemoServlet> getDemoServlet() {
        ServletRegistrationBean<DemoServlet> bean = new ServletRegistrationBean<>();
        List<String> urlMappings = new ArrayList<>();
        urlMappings.add("/demo");
        bean.setServlet(new DemoServlet());
        bean.setUrlMappings(urlMappings);
        bean.setLoadOnStartup(1);
        return bean;
    }

    @Bean
    public ServletListenerRegistrationBean<EventListener> getDemoListener(){
        ServletListenerRegistrationBean<EventListener> bean = new ServletListenerRegistrationBean<>();
        bean.setListener(new DemoListener());
        return bean;
    }

}

完成配置,启动!