Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
## 前言
模版引擎千千萬(wàn),今個(gè)說(shuō)說(shuō)Thymeleaf,主要是不想在混用jsp標(biāo)簽和使用jsp后綴文件,
直接使用html文件,便于前后端分離。
如果覺(jué)得布局不夠美觀,可以看我的個(gè)人博客:http://nealma.com
開(kāi)發(fā)環(huán)境:
OS: Mac 10.11.6
IDE: IDEA
Build: Maven
### 依賴
Spring Boot天生內(nèi)置了對(duì)Thymeleaf的支持,簡(jiǎn)化了配置,加速開(kāi)發(fā)。只需要引入如下
```
<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/文件夾下,存放你的模版文件,其實(shí)在應(yīng)用啟動(dòng)的時(shí)候,
TemplateEngine,ThymeleafViewResolver會(huì)自用實(shí)例化。
### 空間指定
沒(méi)有指定空間,總是飄紅,還是加上吧
```
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
```
### 最簡(jiǎn)用例
* 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", "小怪獸來(lái)了");
Map<String, Object> map1=new HashMap<>();
map1.put("id", 2);
map1.put("title", "小怪獸來(lái)了");
model.addAttribute("list", Arrays.asList(new Object[]{map,map1}));
return new ModelAndView("/index");
}
}
```
* 創(chuàng)建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>
```
### 結(jié)束
使用過(guò)程中,發(fā)現(xiàn)thymeleaf對(duì)于html的語(yǔ)法要求的很嚴(yán)格,每個(gè)標(biāo)簽都要有結(jié)束tag。我的一個(gè)頁(yè)面
<link > <img> 沒(méi)有"/",導(dǎo)致報(bào)錯(cuò);還有就是屬性必須是"=",即key=value, 在input中我使用了disable,結(jié)果報(bào)錯(cuò)了
于是改成disable="disable".
前面我們講解了Spring Boot項(xiàng)目的創(chuàng)建、Spring Boot結(jié)構(gòu)信息,自動(dòng)配置功能等,那么Springboot創(chuàng)建出來(lái),我們最終是要做web開(kāi)發(fā)的,所以我們這章講解如何用SpringBoot做web開(kāi)發(fā)。
Spring boot提供了一套完整的web開(kāi)發(fā)流程,從前端到后臺(tái),再到數(shù)據(jù)庫(kù),定時(shí)任務(wù),消息隊(duì)列等都可以支持.一般利用Spring框架開(kāi)發(fā)一個(gè)Web應(yīng)用有兩種方式:
Spring Boot 提供了spring-boot-starter-web來(lái)為Web開(kāi)發(fā)予以支持,spring-boot-starter-web為我們提供了嵌入的Tomcat以及SpringMVC的依賴,用起來(lái)很方便。另外,我們還要用到模板引擎,用來(lái)顯示視圖頁(yè)面,springboot支持的模板引擎很多,包括Thymeleaf, FreeMarker, Groovy, Mustache, Velocity, JSP等,
之前Java第七模塊講解Thymeleaf時(shí)已經(jīng)講解過(guò)jsp現(xiàn)在不建議使用,我們這里用Thymeleaf來(lái)做模板。
這種方式前端開(kāi)發(fā)和后端開(kāi)發(fā)完全分離,可以由前后端兩個(gè)團(tuán)隊(duì)分開(kāi)同步開(kāi)發(fā),只需要協(xié)商好接口就行,前端負(fù)責(zé)開(kāi)發(fā)頁(yè)面并調(diào)用后端接口展示數(shù)據(jù),后端負(fù)責(zé)提供Restful風(fēng)格的接口.
Thymeleaf相關(guān)知識(shí)看Java第七模塊。
這里直接講解Springboot中怎么整合Themeleaf模板。
我們先在springboot中使用Thymeleaf,看看簡(jiǎn)化了哪些步驟,再來(lái)分析為什么會(huì)簡(jiǎn)化。
選擇web依賴
選擇Thymeleaf依賴
html標(biāo)簽中添加 xmlns:th="http://www.thymeleaf.org"
通過(guò)上面的操作,我們會(huì)發(fā)現(xiàn)我們不需要配置視圖的前綴和后綴了,這是因?yàn)橄到y(tǒng)已經(jīng)幫我自動(dòng)配置了。
自動(dòng)配置信息在:
可以看到 默認(rèn)配置的前綴為templates文件夾
后綴為.html
所以我們只需要把html頁(yè)面建在templates文件夾下就可以。
比如將后綴名改為.htm
先找到后綴名配置名稱:
然后在配置文件application.properties中添加
spring.thymeleaf.suffix=.htm
添加后綴名為.htm的模板文件
運(yùn)行:
對(duì)html+js的傳統(tǒng)設(shè)計(jì),現(xiàn)在很多網(wǎng)站都采用div&css+標(biāo)簽化+模塊化的設(shè)計(jì)。模板引擎根據(jù)一定的語(yǔ)義,將數(shù)據(jù)填充到模板中,產(chǎn)生最終的HTML頁(yè)面。模板引擎主要分兩種:客戶端引擎和服務(wù)端引擎。
客戶端渲染:
模板和數(shù)據(jù)分別傳送到客戶端,在客戶端由JavaScript模板引擎渲染出最終的HTML視圖。將模板渲染放置在客戶端做,可以降低服務(wù)端的壓力,并且如果前端內(nèi)容分別來(lái)自多個(gè)后臺(tái)系統(tǒng),而這些后臺(tái)的架構(gòu)各不相同(Java、.NET、Ruby等),則服務(wù)器端渲染需要采用不同的技術(shù),模板資源無(wú)法共享。
服務(wù)端渲染:
引擎在服務(wù)器端將模板和數(shù)據(jù)合成,返回最終的html頁(yè)面,相對(duì)于客戶端渲染,數(shù)據(jù)存儲(chǔ)更加安全。主要有freemarker、velocity、thymeleaf等。
相較與其他的模板引擎,thymeleaf它有如下三個(gè)特點(diǎn):
(a) 在有網(wǎng)絡(luò)和無(wú)網(wǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁(yè)面的靜態(tài)效果,同時(shí)也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動(dòng)態(tài)頁(yè)面效果。這是由于它支持 html 原型,然后在 html 標(biāo)簽里增加額外的屬性來(lái)達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時(shí)會(huì)忽略未定義的標(biāo)簽屬性,所以 thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁(yè)面時(shí),Thymeleaf 標(biāo)簽會(huì)動(dòng)態(tài)地替換掉靜態(tài)內(nèi)容,使頁(yè)面動(dòng)態(tài)顯示。
(b) 開(kāi)箱即用的特性。它提供標(biāo)準(zhǔn)和spring標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn)JSTL、 OGNL表達(dá)式效果,避免每天套模板、改jstl、改標(biāo)簽的困擾。同時(shí)開(kāi)發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言。
(c) 提供spring標(biāo)準(zhǔn)方言和一個(gè)與 SpringMVC 完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國(guó)際化等功能。
1、新建項(xiàng)目sc-thymeleaf,對(duì)應(yīng)的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啟動(dòng)類
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
說(shuō)明:thymeleaf所有的配置項(xiàng)可以參考類
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties
常用配置說(shuō)明:
# THYMELEAF (ThymeleafAutoConfiguration)
#開(kāi)啟模板緩存(默認(rèn)值:true)
spring.thymeleaf.cache=true
#Check that the template exists before rendering it.
spring.thymeleaf.check-template=true
#檢查模板位置是否正確(默認(rèn)值:true)
spring.thymeleaf.check-template-location=true
#Content-Type的值(默認(rèn)值:text/html)
spring.thymeleaf.content-type=text/html
#開(kāi)啟MVC Thymeleaf視圖解析(默認(rèn)值:true)
spring.thymeleaf.enabled=true
#模板編碼
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的視圖名稱列表,用逗號(hào)分隔
spring.thymeleaf.excluded-view-names=
#要運(yùn)用于模板之上的模板模式。另見(jiàn)StandardTemplate-ModeHandlers(默認(rèn)值:HTML5)
spring.thymeleaf.mode=HTML5
#在構(gòu)建URL時(shí)添加到視圖名稱前的前綴(默認(rèn)值:classpath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
#在構(gòu)建URL時(shí)添加到視圖名稱后的后綴(默認(rèn)值:.html)
spring.thymeleaf.suffix=.html
#Thymeleaf模板解析器在解析器鏈中的順序。默認(rèn)情況下,它排第一位。順序從1開(kāi)始,只有在定義了額外的TemplateResolver Bean時(shí)才需要設(shè)置這個(gè)屬性。
spring.thymeleaf.template-resolver-order=
#可解析的視圖名稱列表,用逗號(hào)分隔
spring.thymeleaf.view-names=
其實(shí)完全可以使用不用配置,但是Spring Boot官方文檔建議在開(kāi)發(fā)時(shí)將緩存關(guān)閉,默認(rèn)為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、新建模板文件
說(shuō)明:Thymeleaf默認(rèn)模板路徑在classpath:/templates/下
6、運(yùn)行ThymeleafApplication.java類,啟動(dòng)項(xiàng)目
7、在瀏覽器輸入http://127.0.0.1:8090/user/list
這里不深入講解Thymeleaf模板引擎的語(yǔ)法,如果想學(xué)習(xí)Thymeleaf的基本語(yǔ)法可以參考https://www.cnblogs.com/ityouknow/p/5833560.html或者自行找些資料學(xué)習(xí)
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。