11

I need to add a listener to my Spring Boot application, in web.xml it looks like

<listener>
 <listener-class>
    org.springframework.web.context.request.RequestContextListener
 </listener-class>
</listener>

I use no-web.xml configuration, so I've got a class like

public class AppFilterConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Filter[] getServletFilters() {
    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding("UTF8");
    filter.setForceEncoding(true);
    Filter[] filters = new Filter[1];
    filters[0] = filter;
    return filters;
}

private int maxUploadSizeInMb = 5 * 1024 * 1024; // 5 MB

@Override
protected Class<?>[] getRootConfigClasses() {
    return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[]{"/"};
}

@Override
protected void registerDispatcherServlet(ServletContext servletContext) {
    super.registerDispatcherServlet(servletContext);
    servletContext.addListener(new HttpSessionEventPublisher());

}

@Override
public void onStartup(ServletContext servletContext) throws ServletException     {

    super.onStartup(servletContext);
    servletContext.addListener(new RequestContextListener());
}

}

As seen from code above, I have added a listener to onStartup(ServletContext servletContext) method, but it doesn't help as I still get

In this case, use RequestContextListener or RequestContextFilter to expose the current request.

this message. How can I properly add a listener to my Spring Boot Application?

Bogdan Timofeev
  • 1,062
  • 3
  • 11
  • 33
  • 1
    And why do you need this? The functionality of the `RequestContextListener` (or filter) is already part of the `DispatcherServlet`. However your config is also wrong as you aren't loading any configuration class (both your `rootConfigClasses` and `servletConfigClasses` return `null` leading to nothing being loaded). – M. Deinum Jul 05 '16 at 12:02
  • Thanks @M.Deinum, I am solving this problem: http://stackoverflow.com/questions/35875098/protecting-rest-api-with-oauth2-error-creating-bean-with-name-scopedtarget-oau – Bogdan Timofeev Jul 05 '16 at 12:18

2 Answers2

15

I created this class and that solved my issue.

@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
Bogdan Timofeev
  • 1,062
  • 3
  • 11
  • 33
2

Write your own listener class which extends from RequestContextListener and register it via annotation. Something like this:

@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
olexd
  • 1,360
  • 3
  • 13
  • 26