This example shows how to register a ViewResolver by overriding the configureViewResolvers() method of WebMvcConfigurer.
Note: Older versions of this tutorial extended WebMvcConfigurerAdapter. That class was deprecated in Spring Framework 5.0, because WebMvcConfigurer has default methods since Java 8, and it was removed in Spring Framework 6.0. Implement WebMvcConfigurer directly instead.
Example
Implementing WebMvcConfigurer
The method ViewResolverRegistry.jsp() registers an InternalResourceViewResolver with a default view name prefix of /WEB-INF/ and a default suffix of .jsp. In the following example, we are customizing the prefix and keeping the default suffix. The configuration class must be annotated with @Configuration and @EnableWebMvc.
package com.logicbig.example;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers (ViewResolverRegistry registry) {
//by default prefix = "/WEB-INF/" and suffix = ".jsp"
registry.jsp().prefix("/WEB-INF/views/");
}
}
Creating the Controller
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping("/")
public String handleRequest (Model model) {
model.addAttribute("msg", "Hello from spring mvc controller.");
return "my-page";
}
}
Creating the JSP page
src/main/webapp/WEB-INF/views/my-page.jsp<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<p> ${msg}</p>
</body>
</html>
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Output
 $ curl -s "http://localhost:8080"
<html> <body> <p> Hello from spring mvc controller.</p> </body> </html>
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 4.1.0.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- JDK 25
- Maven 3.9.11
|