A view controller is nothing but a handler mapping ordered at 1 to map URL paths directly to view names.
If we implement WebMvcConfigurer and override the addViewControllers() method, then an additional HandlerMapping is registered which maps URL paths directly to view names.
Following is the signature of WebMvcConfigurer#addViewControllers()
void addViewControllers(ViewControllerRegistry registry)
package com.logicbig.example;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@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 the following registrations:
- Register a mapping of URL to view.
- Specify a response status code.
- Directly return a status code without a message body.
- Redirect to another URL.
Registering View Controllers by extending WebMvcConfigurationSupport
You can register view controllers by extending WebMvcConfigurationSupport and overriding its addViewControllers method. This approach gives you direct control over Spring MVC's core configuration.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
// Maps the URL "/" to the view named "home"
registry.addViewController("/").setViewName("home");
// Maps the URL "/login" to the view named "login"
registry.addViewController("/login").setViewName("login");
}
}
If you extend WebMvcConfigurationSupport directly, you must not use the @EnableWebMvc annotation on your configuration class. The @EnableWebMvc annotation imports a configuration that is a subclass of WebMvcConfigurationSupport; having both can lead to conflicts and your custom configurations (like view controllers) may not be registered
Examples
|