Close

Spring MVC - Using @RequestMapping without path on a handler method

If there's no @RequestMapping used on the class level and @RequestMapping without path used on a method then it will act as a fallback handler (default handler) and will map to all URLs for which specific matches are not available.

In this case @RequestMapping("") is not equivalent to @RequestMapping. @RequestMapping("") is equivalent to @RequestMapping("/").

Example

@Controller
public class MyController {

  @ResponseBody
  @RequestMapping("")
  public String rootHandler(HttpServletRequest request) {
      return "response from rootHandler()";
  }

  @ResponseBody
  @RequestMapping("test")
  public String testHandler() {
      return "response from testHandler()";
  }

  @ResponseBody
  @RequestMapping
  public String fallbackHandler(HttpServletRequest request) {
      return "response from fallbackHandler for uri: "+request.getRequestURI();
  }
}

Running example

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

If @RequestMapping is used on class level as well

In this case all handler's mappings will be relative to the root (the class level path).

@Controller
@RequestMapping("/app")
public class MyController2 {

  @ResponseBody
  @RequestMapping("") //same as @RequestMapping
  public String appRootHandler(HttpServletRequest request) {
      return "response from appRootHandler()";
  }

  @ResponseBody
  @RequestMapping("test")
  public String appTestHandler() {
      return "response from appTestHandler()";
  }
}
In above class @RequestMapping and @RequestMapping("") cannot be used in the same class as they both will map to the root url and will cause ambiguous mapping exception during startup.

Note that this controller and the last example controller both can live in the same application.

Output

All other relative urls will be mapped to the last controller's fallback handler


Check out this example as well when @RequestMapping without path is used on class level.

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.0.4.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

empty-handler-mapping Select All Download
  • empty-handler-mapping
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyController.java

    See Also