雖然現在前后端大多是分離的,而且是使用json數據傳輸,但是多少我們都要知道一些整合技術的使用。
早些時候,我們使用JSP進行頁面數據開發,如今,JSP已經逐漸退下舞臺。
對于后端開發工程師,最好的頁面交互式使用JSON數據。
本章節作為開發參考。
[TOC]
目錄.jpg
JSP的接班
當今企業級的開發中,前后端是分離的,對于視圖層技術有專業人士去開發,但是SB中對于視圖層也有支持,當即推薦的就是Thymeleaf,以及Freemarker,他們是JSP的的后輩。
Thymeleaf支持HTML原型,方便前端工程師查看樣式,方便后端工程師查看效果。
Thymeleaf的使用
是什么
SB推薦的前端模板引擎,支持HTML原型??梢越Y合HTML,將數據以對象的形式進行顯示。
添加依賴
在pom中添加spring-boot-starter-thymeleaf
依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置Thymeleaf
按理說:自動化配置類ThymeleafAutoConfiguration.class會生成,但是筆者并未看到。
ThymeleafAutoConfiguration.class這個配置類主要是用來進行配置的,如果沒有生成,無妨,自己生成即可,但是不推薦這么做,因為我們改配置通常都用properties進行配置。
application.properties中有相關配置(常用):
# >>>>>>>>>>>>>>>>>>>>>>>>>Thymeleaf config
# 是否開啟緩存,默認true
spring.thymeleaf.cache=true
# 模板是否存在,默認true
spring.thymeleaf.check-template=true
#模板未知是否存在,默認true
spring.thymeleaf.check-template-location=true
# 模板文件編碼
spring.thymeleaf.encoding=UTF-8
# 模板文件地址
spring.thymeleaf.prefix=classpath:/templates/
# Content-Type配置
spring.thymeleaf.servlet.content-type=text/html; charset=utf-8
# 模板文件后綴
spring.thymeleaf.suffix=.html
配置控制器
創建一個POJO對象:Book:
public class Book {
private Integer id;
private String name,author;
……geter/seter
}
創建一個控制類方法:
@GetMapping("/book")
public ModelAndView books() {
System.out.println(">>>>>>>>>>>>>>>>>>>>s");
Book b = new Book();
b.setId(1);
b.setAuthor("Leon");
b.setName("西行記");
Book b2 = new Book();
b2.setId(1);
b2.setAuthor("Leon");
b2.setName("西行記");
ArrayList<Book> books = new ArrayList<Book>();
books.add(b);
books.add(b2);
ModelAndView mModelAndView = new ModelAndView();
mModelAndView.addObject("books",books); // 定義數據對象
mModelAndView.setViewName("book"); // 跳轉到templates中指定頁面book.html
return mModelAndView;
}
請注意setViewName方法他的作用是指向頁面到resources/templates/book.html
視圖顯示
在resource下新建templates文件,在里面新建文件book.html
<!DOCTYPE html>
<html lang='en' xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1">
<tr>
<td>編號</td>
<td>名稱</td>
<td>作者</td>
</tr>
<tr th:each="book:${books}">
<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.author}"></td>
</tr>
</table>
</body>
</html>
運行即可顯示。
FreeMarker
配置方式方法跟Thymeleaf類似,在視圖顯示的時候會有稍許不同。
請各位看官自行百度即可。