How to add a RequestContextListener with no-xml configuration?
Asked Answered
S

2

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?

Silvery answered 5/7, 2016 at 11:45 Comment(2)
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).Dorian
Thanks @M.Deinum, I am solving this problem: #35875598Silvery
S
15

I created this class and that solved my issue.

@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
Silvery answered 8/7, 2016 at 10:52 Comment(0)
D
2

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

@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
Damato answered 5/7, 2016 at 12:46 Comment(1)
Thanks for the supplementation. Glad to be helpful.Damato

© 2022 - 2024 — McMap. All rights reserved.