If we do not register any ViewResolver explicitly, either by overriding configureViewResolvers(ViewResolverRegistry) of WebMvcConfigurer or by declaring one as a @Bean, Spring MVC falls back to an instance of InternalResourceViewResolver by default. Its prefix and suffix properties are both empty strings. That means the view name returned by a controller is used as-is, so we have to return the full path of the view resource (for example, a JSP file). Let's see this in an example.
Example
The JavaConfig
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.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {
//no ViewResolver registration
}
A 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 "/WEB-INF/views/my-page.jsp";
}
}
Note that we have to return the full view path from our controller, including the file extension.
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>
The JSP is placed under WEB-INF, so browsers cannot request it directly. It can only be reached when the request is forwarded to it by the view resolver.
Output
 $ curl -s "http://localhost:8080"
<html> <body> <p> Hello from spring mvc controller.</p> </body> </html>
Note: This example fails with Spring version 4.1.0.RELEASE with following error: Could not resolve view with name '/WEB-INF/views/my-page.jsp' Issue: SPR-12267. Works for all other versions.
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.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
|