2013-04-12 35 views
1

我已經用WebApplicationInitializer搜索了no-web.xml配置的一些代碼。如何使用WebApplicationInitializer初始化dispatcherServlet?

這些代碼是相同的格式。

  1. 創建rootContext
  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()); 
} 

是不是?我在春季幫助文檔中看到了第一個代碼。但它不能與碼頭9一起工作。

+0

您正在使用哪個版本的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 – Jan

回答

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

+0

它可以工作。謝謝。我使用了jetty的9.0.0版本。謝謝你1月。 – xyzlast

0

這是碼頭的問題。 Jetty無法使用ContextLoaderListener初始化rootContext。

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

相關問題