【问题标题】:How initialize dispatcherServlet using WebApplicationInitializer?如何使用 WebApplicationInitializer 初始化 dispatcherServlet?
【发布时间】:2013-04-12 10:39:22
【问题描述】:

我已经使用 WebApplicationInitializer 搜索了一些用于 no-web.xml 配置的代码。

这些代码格式相同。

  1. 创建根上下文
  2. 创建 ContextLoaderListener
  3. 向 servlet 注册监听器

这里是代码块

    @Override
public void onStartup(ServletContext servletContext) throws ServletException {
    registerListener(servletContext);
    registerDispatcherServlet(servletContext);
}

private void registerListener(ServletContext servletContext) {
    AnnotationConfigWebApplicationContext rootContext = createContext(DomainConfiguration.class);
    ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);
    servletContext.addListener(contextLoaderListener);
    servletContext.addListener(new RequestContextListener());
}

private void registerDispatcherServlet(ServletContext servletContext) {
    AnnotationConfigWebApplicationContext dispatcherContext = createContext(WebMvcContexConfiguration.class);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
            new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(annotatedClasses);
    return context;
}

但是,此代码不起作用。它无法在根上下文中找到上下文对象。 所以,我已经更改了一些代码,它正在工作。

这是工作代码。

    private void registerListener(ServletContext servletContext) {
    AnnotationConfigWebApplicationContext rootContext = createContext(DomainConfiguration.class);
    ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);
    // This is changed code!!
    contextLoaderListener.initWebApplicationContext(servletContext);
    servletContext.addListener(new RequestContextListener());
}

对吗?我在 spring 帮助文档中看到了第一个代码。但它不适用于 jetty 9。

【问题讨论】:

标签: spring-mvc web jetty tomcat7


【解决方案1】:

您使用的是哪个版本的 jetty-9? jetty-9.0.0.RC3 中修复了一个问题(参考:https://bugs.eclipse.org/bugs/show_bug.cgi?id=400312),这意味着此类代码添加的任何侦听器都不会被调用。请尝试使用 jetty-9.0.1 版本的原始代码。如果它不起作用,请在此处提出错误并在码头问题跟踪器中包含代码示例:https://bugs.eclipse.org/bugs/enter_bug.cgi?product=Jetty

【讨论】:

  • 它有效。谢谢你。我使用了 9.0.0 版本的 jetty。谢谢一月。
【解决方案2】:

这是码头的问题。 Jetty 无法使用 ContextLoaderListener 初始化 rootContext。

我不知道原因。但是tomcat7现在正在工作。

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2020-08-02
    • 2017-11-06
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多