BeanNameUrlHandlerMapping maps requests by controller beans names. The handler sees bean name as URI to match.
This handler is registered by default. To let this HandlerMapping working, all we have to do to specify the name of the controller bean starting with "/". Let's see an example how to do that.
Registering the controller with a name
@EnableWebMvc
@Configuration
public class AppConfig {
@Bean("/example")
public BeanNameExampleController exampleController () {
return new BeanNameExampleController();
}
}
The controller
@Controller
public class BeanNameExampleController {
@RequestMapping
@ResponseBody
public String handleRequest () {
return "response from /example";
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
In above example, we must not specify the URI path with 'value' element of @RequestMapping, otherwise RequestMappingHandlerMapping will be used (it's order is 0, check out the last tutorial to understand ordering)
Note that, if we use @ComponentScan , instead of @Bean factory methods, then we have to use 'value' element as @Controller("/example") or JSR-330 annotation @Named("/example") on the controller class.
Example ProjectDependencies and Technologies Used: - spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
- javax.servlet-api 3.0.1 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|