Close

Spring MVC - Using default ViewResolver

[Last Updated: Jul 29, 2017]

If we do not register any ViewResolver explicitly by either overriding WebMvcConfigurerAdapter or by directly registering it via @Bean, an instance of InternalResourceViewResolver will be used by default whose 'prefix' and 'suffix' properties set to empty strings. That means, we have to use full view paths in our application. Let's understand that with example.

Example

The JavaConfig

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig extends WebMvcConfigurerAdapter {
  //no ViewResolver registration
}

A Controller

@Controller
public class MyController {
  
  @RequestMapping("/")
  public String handleRequest (Model model) {
      model.addAttribute("msg", "Hello from spring mvc controller.");
      return "/WEB-INF/views/my-page.jsp";
  }
}

Note that, we have to return full view path from our controller.

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

Using default ViewResolver Select All Download
  • view-resolver-default-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyController.java
          • webapp
            • WEB-INF
              • views

    See Also