Spring boot中使用JSP
创建jsp页面
在pom.xml文件中引入依赖
<!--引入Spring Boot内嵌的Tomcat对JSP的解析包-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->
<!-- jsp依赖jar包start -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- jsp依赖jar包end -->
<!--jstl标签依赖的jar包start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--jstl标签依赖的jar包end -->
在application.properties文件中配置视图
#配置视图的前后缀
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
编写books.jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>书籍列表展示</title>
</head>
<body>
<table border="1" width="100%" class="imagetable">
<tr>
<th>序号</th>
<th>名称</th>
<th>价格</th>
<th>作者</th>
<th>描述</th>
</tr>
<c:if test="${not empty books}">
<c:forEach items="${books}" var="book" >
<tr>
<td>${book.id}</td>
<td>${book.name}</td>
<td>${book.price}</td>
<td>${book.author}</td>
<td>${book.description}</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
编写Controller来跳转JSP页面
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping("/findBooks")
public String findBooks(Model model) {
List<Book> books = new ArrayList<>();
Book book = new Book();
book.setId(1L);
book.setName("Java编程思想");
book.setPrice(89.99);
book.setAuthor("Bruce Eckel");
book.setDescription("《计算机科学丛书:Java编程思想(第4版)》赢得了全球程序员的广泛赞誉,即使是晦涩的概念,在BruceEckel的文字亲和力和小而直接的编程示例面前也会化解于无形。");
books.add(book);
model.addAttribute("books",books);
return "books";
}
}
进行测试
报错:找不到jsp页面,是因为编译后找不到是jsp页面
解决:在pom.xml文件下添加resources标签
<resources>
<resource>
<!--将src/main/webapp下的页面编译到META-INF/reources中-->
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
再次访问测试