Spring Boot default Thymeleaf as a template engine, JSP file and direct deposit can not normally access, in the main directory need to create a new folder to store JSP files and need to add a dependency in the template directory.
1. Create a directory for JSP files
First, main
create a directory webapp
catalog (any name can be), then it will be added to the Project Structure Web Resource Directory.
2. Add dependence
Add depend in pom.xml to support JSTL and JSP:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
3. MVC configuration
Edit application.yml:
spring:
mvc:
view:
suffix: .jsp
prefix: /view/
Disposed relative path prefix JSP file is stored (here a JSP file in view
directory), suffix .jsp
.
4. Write controllers and page
IndexController
:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class IndexController {
@RequestMapping("/")
public ModelAndView index() {
ModelAndView index = new ModelAndView("index");
index.addObject("message", "Hello, Spring Boot!");
return index;
}
}
index.jsp
:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Spring Boot with JSP</h1>
<h2>${message}</h2>
</body>
</html>
5. Access page
Access http://localhost:8080/
: