1. 在pom.xml文件中配置以下依赖项
<!--引入Spring Boot内嵌的Tomcat对JSP的解析包,不加解析不了jsp页面-->
<!--如果只是使用JSP页面,可以只添加该依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
2. 在pom.xml的build标签中要配置以下信息
SpringBoot要求jsp文件必须编译到指定的META-INF/resources目录下才能访问,否则访问不到。其实官方已经更建议使用模板技术(后面会讲模板技术)
<!--强制编译资源-->
<resources>
<resource>
<!--源文件位置-->
<directory>src/main/webapp</directory>
<!--指定编译到META-INF/resources,该目录不能随便写-->
<targetPath>META-INF/resources</targetPath>
<includes>
<!--指定要把哪些文件编译进去,**表示webapp目录及子目录,*.*表示所有文件-->
<include>**/*.jsp</include>
</includes>
</resource>
</resources>
3. application.properties文件配置Spring MVC的视图展示为jsp,这里相当于Spring MVC的配置
server.port=9002
server.servlet.context-path=/002-springboot-jsp
#配置SpringMVC的视图解析器
#其中:/相当于src/main/webapp目录
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
4. 在com.suke.springboot.web包下创建SpringBootController类,并编写代码
@Controller
public class SpringBootController {
@RequestMapping(value = "/springBoot/jsp")
public String jsp(Model model) {
System.out.println("-------jsp-------");
model.addAttribute("data", "SpringBoot 前端使用JSP页面!");
return "index";
}
}
5. 在src/main下创建一个webapp目录
(1)右击 main 选择 New --》Directory
(2)选择 main\webapp 资源文件
(3)更改Web资源目录为webapp和发布工程根目录的匹配路径
(4)点击Create Artifact 创建 OK
(5) 创建WEB-INF目录并新建web.jsp页面
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
6. 在webapp目录下新建index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${data}
<c:forEach items="" varStatus="st" >
</c:forEach>
</body>
</html>
7. 重新运行Application,通过浏览器访问测试