从Eclipse中运行Tomcat总是给我404(但index.html有效)



我的第一个软件堆栈:

  • Eclipse 4.2
  • Tomcat 7.0.37
  • 带有m2e插件的Maven
  • javax.servlet 3.0.1
  • Spring WebMVC和Spring Web 3.2.1

我使用的servlet 3没有web.xml.

我做了什么:

  • Eclipse->新的Maven项目
  • 编辑pom.xml:添加Spring和javax.servlet
  • Eclipse->项目属性->项目方面->添加动态web方面
  • Eclipse->项目属性->部署程序集->删除WebContent并添加/src/main/webapp
  • javax.servlet.ServletContainerInitializer添加到/src/main/webapp/META-INF/services中,并放入实现WebApplicationInitializer的完全限定类名中

目前,我的项目包含大约7个文件(3x.java、1x.jsp、1x.html、1x.pom、1xjavax.servlet.ServletContainerInitializer)

什么有效:

通过Maven编译和war打包,然后在独立的Tomcat上简单地部署.war。

  • http://127.0.0.1/MyApp/显示index.html
  • http://127.0.0.1/MyApp/hello显示hello.jsp

什么不起作用:

如果我现在尝试通过Run -> Run on Server使用Eclipse。然后我选择Tomcat目录,等等。servlet(/hello)只给出一个404。但是index.html是有效的。

三个Java文件:

Initializer.java:

public class Initializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");    
    }
}

WebAppConfig.java:

@Configuration
@ComponentScan("myapp.server")
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
    @Bean
    public InternalResourceViewResolver setupViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

FooController.java:

@Controller
public class FooController { 
    @RequestMapping("/hello")
    public String helloWorld(Model model) {
        model.addAttribute("wisdom", "Goodbye XML");
        return "hello";
    }
}

如果你需要更多的信息,请告诉我。

谢谢!!

编辑:如果Tomcat是通过Eclipse启动的,我在哪里可以找到它的日志文件?

输出:

Eclipse控制台(这一切都是在启动Tomcat之后发生的,即使我调用了http://localhost:8080/http://localhost:8080/MyApp/之类的URL,它也不会更改):http://pastebin.com/gGn0j48T

Tomcat日志似乎保存在.metadata/.plugins/org.eclipse.wst.server.core/tmp0/logs/中。只有一个文件localhost_access_log.2013-02-20.txt,输出看起来并不有趣:http://pastebin.com/QmD4wPmA

现在我这样做是为了获得catalina.out:https://stackoverflow.com/a/5045247/1321564

以下是重新启动Tomcat并尝试一些URL后的输出:文件保持为空?!

我还意识到Tomcat上的以下目录是空的:wtpwebapps/MyApp/WEB-INF/lib/。里面不应该有一些Spring libs吗?!

成功了!!!

如上所述:WEB-INF/lib文件夹中没有Spring库。

因为我在用Maven。解决方案非常简单:

  • 右键单击项目
  • 单击Properties
  • 单击Deployment Assembly
  • 单击Add...
  • 选择Java Build Path Entries
  • 单击Next
  • 选择Maven Dependencies
  • 单击Finish

重新启动服务器。

现在我可以在服务器视图中看到不同:

  • 展开Tomcat服务器。现在您可以看到该项目
  • 展开项目现在列出了spring-web-3.2.1.RELEASE.jar。以前不是这样

最新更新