WebApplicationInitializer container.addServlet()返回null

Mat*_*ttG 7 eclipse web-applications spring-data

我正在使用maven创建一个基本的Web应用程序,然后导入到Eclipse 4.2.我将Tomcat 7设置为服务器.我正在尝试使用mongodb为Web应用程序配置spring数据.

我遵循这里找到的基于代码的配置方法:WebApplicationInitializer

当我在服务器上运行项目时,我在我创建的WebApplicationInitializer类中得到一个空指针异常.行:container.addServlet("dispatcher",new DispatcherServlet(dispatcherContext)); 返回null.

我错过了什么?我使用注释从头开始创建Web应用程序有点新鲜.

这是有问题的课程:

public class ATWWebAppInitializer implements WebApplicationInitializer
{
    @Override
    public void onStartup(ServletContext container) throws ServletException  
    {
      // Create the 'root' Spring application context
      AnnotationConfigWebApplicationContext rootContext = new  AnnotationConfigWebApplicationContext();
      rootContext.register(SpringMongoConfig.class);

      // Manage the lifecycle of the root application context
      container.addListener(new ContextLoaderListener(rootContext));

      // Create the dispatcher servlet's Spring application context
      AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
      dispatcherContext.register(ATWDispatcherConfig.class);

      // Register and map the dispatcher servlet
      ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/*");
    }
} 
Run Code Online (Sandbox Code Playgroud)

尝试将此添加到POM:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

没有改变任何东西,仍然得到了NPE.我在这里读到(http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html)如果servlet已经注册,container.addServlet会返回null吗?Tomcat已经注册了一个servlet吗?

为浪费每个人的时间道歉,我有一个web.xml文件也注册了相同的servlet. 所以这个只返回null.现在要修复404,可能会以某种方式搞砸控制器.

Rav*_*Rao 10

根据ServletContext JavaDoc,如果已经注册了具有指定名称的servlet,则方法addServlet()将返回null.