java 如何添加无 xml 配置的 RequestContextListener?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38202621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a RequestContextListener with no-xml configuration?
提问by Bogdan Timofeev
I need to add a listener to my Spring Boot application, in web.xml it looks like
我需要在我的 Spring Boot 应用程序中添加一个监听器,在 web.xml 中它看起来像
<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
我使用 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());
}
}
As seen from code above, I have added a listener to onStartup(ServletContext servletContext) method, but it doesn't help as I still get
从上面的代码可以看出,我在 onStartup(ServletContext servletContext) 方法中添加了一个监听器,但它没有帮助,因为我仍然得到
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?
这条信息。如何正确地向 Spring Boot 应用程序添加侦听器?
回答by Bogdan Timofeev
I created this class and that solved my issue.
我创建了这个类并解决了我的问题。
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
回答by olexd
Write your own listener class which extends from RequestContextListener
and register it via annotation. Something like this:
编写您自己的侦听器类,RequestContextListener
它通过注解扩展并注册它。像这样的东西:
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}