Spring Boot 默認使用 Thymeleaf 作為模板引擎,直接在 template 目錄中存放 JSP 文件並不能正常訪問,需要在 main 目錄下新建一個文件夾來存放 JSP 文件,而且需要添加依賴。
1. 創建目錄存放 JSP 文件
首先在 main
目錄下新建一個 webapp
目錄(任何名稱都可以),然后在 Project Structure 中將它添加到 Web Resource Directory。
2. 添加依賴
在 pom.xml 中添加依賴以支持 JSTL 和 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 配置
編輯 application.yml:
spring:
mvc:
view:
suffix: .jsp
prefix: /view/
設置前綴為 JSP 文件存放的相對路徑(這里將 JSP 文件放在 view
目錄),后綴為 .jsp
。
4. 編寫控制器和頁面
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. 訪問頁面
訪問 http://localhost:8080/
: