Spring MVC - Setting up ViewResolver by extending WebMvcConfigurerAdapter

[Updated: Jul 29, 2017, Created: Jul 29, 2017]

This example shows how to register a ViewResolver by overriding configureViewResolvers() method of WebMvcConfigurerAdapter.

Example

Extending WebMvcConfigurerAdapter

The method ViewResolverRegistry.jsp() will register InternalResourceViewResolver with a default view name prefix of "/WEB-INF/" * and a default suffix of ".jsp". In the following example, we are customizing prefix:

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig extends WebMvcConfigurerAdapter {
  
  @Override
  public void configureViewResolvers (ViewResolverRegistry registry) {
      //by default prefix = "/WEB-INF/" and  suffix = ".jsp"
      registry.jsp().prefix("/WEB-INF/views/");
  }
}

Writing Controller

@Controller
public class MyController {
  
  @RequestMapping("/")
  public String handleRequest (Model model) {
      model.addAttribute("msg", "Hello from spring mvc controller.");
      return "my-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>

Output

Example Project

Dependencies and Technologies Used :

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

Overriding WebMvcConfigurerAdapter#configureViewResolvers Example Select All Download
  • view-resolver-registry-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views

See Also