Spring Boot 默认使用 Thymeleaf 做为模板引擎,直接在 template 目录中存放 JSP 文件并不能正常访问,须要在 main 目录下新建一个文件夹来存放 JSP 文件,并且须要添加依赖。html
首先在 main
目录下新建一个 webapp
目录(任何名称均可以),而后在 Project Structure 中将它添加到 Web Resource Directory。java
在 pom.xml 中添加依赖以支持 JSTL 和 JSP:web
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency>
编辑 application.yml:spring
spring: mvc: view: suffix: .jsp prefix: /view/
设置前缀为 JSP 文件存放的相对路径(这里将 JSP 文件放在 view
目录),后缀为 .jsp
。apache
IndexController
:tomcat
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
:mvc
<%@ 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>
访问 http://localhost:8080/
:app