I have introduced you to the InternalResourceViewResolver in Spring MVC in the previous tutorial. So in Spring Boot, how do we use InternalResourceViewResolver? In this article, let’s find out.
First, I will create a Spring Boot project with spring-boot-starter-web as follows:
Someone who does not know how to create Spring Boot project in Spring Tool Suite, can refer to this tutorial.
In this example, we will run the application using the Tomcat server, but because when we created the Spring Boot project, this project did not include the tomcat-embed-jasper library to render the JSP files, so we need to add its dependency to the pom.xml file as follows:
1 2 3 4 5 |
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> |
To use the InternalResourceViewResolver in Spring Boot, there are three things we need to do:
First, we need to have the view file.
In this example, we will create a new view file called home.jsp located in /src/main/webapp/WEB-INF/views:
with the following content:
1 |
Hello World! |
Next, we will need to define a request using our view file name.
To do this, I will create a new controller named HelloController in the package com.huongdanjava.springboot as follows:
with a hello() method defining a “/hello” request that uses the “home” view name as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava.springboot; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("/hello") public String home() { return "home"; } } |
The last step we need to do is: declare the InternalResourceViewResolver in the Spring container.
No need to configure complex as in Spring MVC, Spring Boot support us some properties to configure InternalResourceViewResolver. Just open the application.properties file located in /src/main/resources and declare the following properties:
1 2 |
spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp |
At this point, Spring Boot will use these properties to map the view with the view files located in the /WEB-INF /views/ directory.
Now, just run it.
Result: