Spring boot中使用JSP
阿新 • • 發佈:2018-12-12
建立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>
再次訪問測試