WebMvcConfigurationSupport#viewControllerHandlerMapping() method, by default, registers EmptyHandlerMapping. If we extend WebMvcConfigurerAdapter and override following method, then another HandlerMapping is registered which maps URL paths directly to view names.
@EnableWebMvc
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers (ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("myView");
}
.............
}
Understanding ViewControllerRegistry
With ViewControllerRegistry, we can do following registrations:
- Register a mapping of url to view.
- Specify a response status code.
- Directly returning a status code without a message body.
- Redirecting to another URL.
The HandlerMapping registered by WebMvcConfigurationSupport
Let's see the code snippet (version 4.3.10.RELEASE), how HandlerMapping is registered (I have added the comments to understand what's going on):
public class WebMvcConfigurationSupport implements ..... {
............
@Bean
public HandlerMapping viewControllerHandlerMapping() {
ViewControllerRegistry registry = new ViewControllerRegistry();
registry.setApplicationContext(this.applicationContext);
addViewControllers(registry); 1
AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); 2
handlerMapping = (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping()); 3
handlerMapping.setPathMatcher(mvcPathMatcher());
handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
handlerMapping.setInterceptors(getInterceptors());
handlerMapping.setCorsConfigurations(getCorsConfigurations());
return handlerMapping;
}
............
}
1 This is where our WebMvcConfigurerAdapter#addViewControllers() is called.
2 ViewControllerRegistry#getHandlerMapping() returns an instance of SimpleUrlHandlerMapping (with Order 1), which maps our specified URL paths to ParameterizableViewController. The ParameterizableViewController class implements Controller and always returns our specified view name from its handleRequest() method. If for some reasons we cannot extend WebMvcConfigurerAdapter and override addViewControllers() , we can set up this controller directly.
3 If we did not override WebMvcConfigurerAdapter#addViewControllers() and registered some view controllers then 'handlerMapping' will be null at this point and it will be assigned to an instance of EmptyHandlerMapping . The EmptyHandlerMapping class is defined as a private static subclass of WebMvcConfigurationSupport whose getHandler() method always returns null. Its order is Integer.MAX.
Examples
|