Spring boot convert web.xml listener

drenda picture drenda · Feb 17, 2015 · Viewed 21.9k times · Source

I'm trying to convert my project to Spring Boot project (executable jar file with Jetty embedded). All works with a standard example but I want migrate my old web.xml to Spring Boot.

I migrated Servlet and Filters but I don't understand how migrate filters as this:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
    <listener-class>org.granite.config.GraniteConfigListener</listener-class> 
</listener> 
    <listener>
    <listener-class>org.granite.gravity.websocket.GravityWebSocketDeployer</listener-class>
</listener>

I created my @SpringBootApplication class and I wrote inside all the configuration:

@Bean
@Order(1)
public FilterRegistrationBean springSecurityFilterChain() {     
    FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
    DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy();
    filterRegBean.setFilter(delegatingFilterProxy);
    List<String> urlPatterns = new ArrayList<String>();
    urlPatterns.add("/*");
    filterRegBean.setUrlPatterns(urlPatterns);
    return filterRegBean;
}

Someone can explain me how Listeners should be converted?

Answer

Andy Wilkinson picture Andy Wilkinson · Feb 17, 2015

Spring Boot will automatically register any @Beans of the following types with the servlet container:

  • ServletContextAttributeListener
  • ServletRequestListener
  • ServletRequestAttributeListener
  • HttpSessionAttributeListener
  • HttpSessionListener
  • ServletContextListener

For example, to register GravityWebSocketDeployer which is a ServletContextListener add a @Bean method to your configuration class:

@Bean
public GravityWebSocketDeployer gravityWebSocketDeployer() {
    return new GravityWebSocketDeployer();
}