## 前言
模版引擎千千萬,今個說說Thymeleaf,主要是不想在混用jsp標簽和使用jsp后綴文件,
直接使用html文件,便于前后端分離。
如果覺得布局不夠美觀,可以看我的個人博客:http://nealma.com
開發環境:
OS: Mac 10.11.6
IDE: IDEA
Build: Maven
### 依賴
Spring Boot天生內置了對Thymeleaf的支持,簡化了配置,加速開發。只需要引入如下
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
### 配置
在application.properties文件里加入如下
```
#thymeleaf
#我傾向于放在webapp/WEB-INF的目錄下,spring.thymeleaf.prefix=/templates
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
```
在src/main/resources/templates/文件夾下,存放你的模版文件,其實在應用啟動的時候,
TemplateEngine,ThymeleafViewResolver會自用實例化。
### 空間指定
沒有指定空間,總是飄紅,還是加上吧
```
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
```
### 最簡用例
* Controller
```
/**
*
* 商品信息
*/
@RestController
public class GoodsPageController extends BaseController {
/**
* 商品列表
*/
@RequestMapping(value={"/goods/list"}, method=RequestMethod.GET)
@PermitAll
public ModelAndView list(Model model) {
LOGGER.info("|--> {}", this.getRequest().getRequestURI());
model.addAttribute("name", "neal");
Map<String, Object> map=new HashMap<>();
map.put("id", 1);
map.put("title", "小怪獸來了");
Map<String, Object> map1=new HashMap<>();
map1.put("id", 2);
map1.put("title", "小怪獸來了");
model.addAttribute("list", Arrays.asList(new Object[]{map,map1}));
return new ModelAndView("/index");
}
}
```
* 創建src/main/resources/templates/index.html
```
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Thymeleaf Mini Demo</title>
</head>
<body>
Hello, <b th:text="${name}">Name</b>
<div th:each="item:${list}">
<b th:text="${item.id}">ID</b>
<b th:text="${item.title}">Title</b>
</div>
</body>
</html>
```
### 結束
使用過程中,發現thymeleaf對于html的語法要求的很嚴格,每個標簽都要有結束tag。我的一個頁面
<link > <img> 沒有"/",導致報錯;還有就是屬性必須是"=",即key=value, 在input中我使用了disable,結果報錯了
于是改成disable="disable".
前面我們講解了Spring Boot項目的創建、Spring Boot結構信息,自動配置功能等,那么Springboot創建出來,我們最終是要做web開發的,所以我們這章講解如何用SpringBoot做web開發。
Spring boot提供了一套完整的web開發流程,從前端到后臺,再到數據庫,定時任務,消息隊列等都可以支持.一般利用Spring框架開發一個Web應用有兩種方式:
Spring Boot 提供了spring-boot-starter-web來為Web開發予以支持,spring-boot-starter-web為我們提供了嵌入的Tomcat以及SpringMVC的依賴,用起來很方便。另外,我們還要用到模板引擎,用來顯示視圖頁面,springboot支持的模板引擎很多,包括Thymeleaf, FreeMarker, Groovy, Mustache, Velocity, JSP等,
之前Java第七模塊講解Thymeleaf時已經講解過jsp現在不建議使用,我們這里用Thymeleaf來做模板。
這種方式前端開發和后端開發完全分離,可以由前后端兩個團隊分開同步開發,只需要協商好接口就行,前端負責開發頁面并調用后端接口展示數據,后端負責提供Restful風格的接口.
Thymeleaf相關知識看Java第七模塊。
這里直接講解Springboot中怎么整合Themeleaf模板。
我們先在springboot中使用Thymeleaf,看看簡化了哪些步驟,再來分析為什么會簡化。
選擇web依賴
選擇Thymeleaf依賴
html標簽中添加 xmlns:th="http://www.thymeleaf.org"
通過上面的操作,我們會發現我們不需要配置視圖的前綴和后綴了,這是因為系統已經幫我自動配置了。
自動配置信息在:
可以看到 默認配置的前綴為templates文件夾
后綴為.html
所以我們只需要把html頁面建在templates文件夾下就可以。
比如將后綴名改為.htm
先找到后綴名配置名稱:
然后在配置文件application.properties中添加
spring.thymeleaf.suffix=.htm
添加后綴名為.htm的模板文件
運行:
對html+js的傳統設計,現在很多網站都采用div&css+標簽化+模塊化的設計。模板引擎根據一定的語義,將數據填充到模板中,產生最終的HTML頁面。模板引擎主要分兩種:客戶端引擎和服務端引擎。
客戶端渲染:
模板和數據分別傳送到客戶端,在客戶端由JavaScript模板引擎渲染出最終的HTML視圖。將模板渲染放置在客戶端做,可以降低服務端的壓力,并且如果前端內容分別來自多個后臺系統,而這些后臺的架構各不相同(Java、.NET、Ruby等),則服務器端渲染需要采用不同的技術,模板資源無法共享。
服務端渲染:
引擎在服務器端將模板和數據合成,返回最終的html頁面,相對于客戶端渲染,數據存儲更加安全。主要有freemarker、velocity、thymeleaf等。
相較與其他的模板引擎,thymeleaf它有如下三個特點:
(a) 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,同時也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由于它支持 html 原型,然后在 html 標簽里增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標簽屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標簽會動態地替換掉靜態內容,使頁面動態顯示。
(b) 開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、改jstl、改標簽的困擾。同時開發人員也可以擴展和創建自定義的方言。
(c) 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。
1、新建項目sc-thymeleaf,對應的pom.xml文件如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring-cloud</groupId> <artifactId>sc-thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sc-thymeleaf</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> </project>
2、新建springboot啟動類
package sc.thymeleaf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ThymeleafApplication { public static void main(String[] args) { SpringApplication.run(ThymeleafApplication.class, args); } }
3、新建配置文件application.yml
server: port: 8090 spring: application: name: sc-thymeleaf thymeleaf: cache: false
說明:thymeleaf所有的配置項可以參考類
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
常用配置說明:
# THYMELEAF (ThymeleafAutoConfiguration)
#開啟模板緩存(默認值:true)
spring.thymeleaf.cache=true
#Check that the template exists before rendering it.
spring.thymeleaf.check-template=true
#檢查模板位置是否正確(默認值:true)
spring.thymeleaf.check-template-location=true
#Content-Type的值(默認值:text/html)
spring.thymeleaf.content-type=text/html
#開啟MVC Thymeleaf視圖解析(默認值:true)
spring.thymeleaf.enabled=true
#模板編碼
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的視圖名稱列表,用逗號分隔
spring.thymeleaf.excluded-view-names=
#要運用于模板之上的模板模式。另見StandardTemplate-ModeHandlers(默認值:HTML5)
spring.thymeleaf.mode=HTML5
#在構建URL時添加到視圖名稱前的前綴(默認值:classpath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
#在構建URL時添加到視圖名稱后的后綴(默認值:.html)
spring.thymeleaf.suffix=.html
#Thymeleaf模板解析器在解析器鏈中的順序。默認情況下,它排第一位。順序從1開始,只有在定義了額外的TemplateResolver Bean時才需要設置這個屬性。
spring.thymeleaf.template-resolver-order=
#可解析的視圖名稱列表,用逗號分隔
spring.thymeleaf.view-names=
其實完全可以使用不用配置,但是Spring Boot官方文檔建議在開發時將緩存關閉,默認為true
4、新建Controller
package sc.thymeleaf.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import sc.thymeleaf.model.User; @Controller public class UserController { @RequestMapping("/user/list") public String userList2(Model model) throws Exception { model.addAttribute("hello", "Hello, thymeleaf!"); List<User> list=new ArrayList<User>(); User u1=new User(); u1.setId(1); u1.setName("huangjinjin"); u1.setAge(30); u1.setPosition("cto"); list.add(u1); User u2=new User(); u2.setId(2); u2.setName("huang ge"); u2.setAge(32); u2.setPosition("cco"); list.add(u2); model.addAttribute("list", list); return "/user/list"; } }
5、新建模板文件
說明:Thymeleaf默認模板路徑在classpath:/templates/下
6、運行ThymeleafApplication.java類,啟動項目
7、在瀏覽器輸入http://127.0.0.1:8090/user/list
這里不深入講解Thymeleaf模板引擎的語法,如果想學習Thymeleaf的基本語法可以參考https://www.cnblogs.com/ityouknow/p/5833560.html或者自行找些資料學習
*請認真填寫需求信息,我們會在24小時內與您取得聯系。