Using Spring MVC, I want to map the root path of my Java web application to a controller.
Controller class :
package project.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
@RequestMapping(value={"/", "/index"})
public String home() {
return "index";
}
}
The home() method is mapped on “/” and “/index” url fragments. /index works fine:
http://localhost:8080/JavaSpringWebProject/index
But “/” generates an http 404 error.
http://localhost:8080/JavaSpringWebProject/
I used the debugger to see if the doService() method in the DispatcherServlet is called as it should be. It is called with /index but not with /. My guess is that Tomcat (v7) does not call the DispatcherServlet. But why?
I’ve created a test project (Dynamic Web project from Eclipse WTP) with Spring 4.0.6 to isolate the problem. It can be checked out from svn at http://code.google.com/p/basic-spring-java/
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Project</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Why is my controller not activated with the “/” path? Many thanks!