我需要在我的Spring Boot应用程序中添加一个监听器,在web.xml中它看起来像
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
我使用no-web.xml配置,所以我有一个像
这样的类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());
}
}
从上面的代码中可以看出,我已经为onStartup(ServletContext servletContext)方法添加了一个监听器,但是它仍然没有帮助,因为我仍然得到
In this case, use RequestContextListener or RequestContextFilter to expose the current request.
这条消息。如何在Spring Boot Application中正确添加监听器?
答案 0 :(得分:8)
我创建了这个类,这解决了我的问题。
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
答案 1 :(得分:2)
编写自己的侦听器类,该类从RequestContextListener
扩展并通过注释进行注册。像这样:
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}