如何使用Thymeleaf和Webjars

1.添加Thymeleaf和Webjars依賴

thymeleaf模板引擎依賴
<groupId>org.springframework.boot</groupId> 3
<artifactId>spring-boot-starter-thymeleaf</artifactId> 4
</dependency>
Webjars模板引擎依賴
<dependency> 
<groupId>org.webjars</groupId> 
<artifactId>bootstrap</artifactId> 
<version>3.3.7-1</version> 
</dependency> 

2.代碼目錄結(jié)構(gòu)

1.png

resources下static?件夾存放images、css、js等靜態(tài)資源
templates存放Thymeleaf模板??

3.Controller層代碼寫法

package com.example.quickstart.controller; 

import com.example.quickstart.entity.Student; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.GetMapping; 
import javax.annotation.Resource; 

@Controller 
public class IndexController { 

    //注入了一個Student類的對象,被Spring容器托管——bean 
    @Resource 
    private Student student; 

    //Get請求映射 
    @GetMapping("index") 
    public String index(ModelMap map) { 
    student.setName("Tom"); 
    student.setAge(20); 
    student.setMale("男"); 
    //將模型加入視圖 
    map.addAttribute("student",student); 
    return "index"; 
  } 
} 

4. html??頭部添加thymeleaf名稱空間聲明

<html xmlns:th="http://www.thymeleaf.org"> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>主頁</title> 
</head> 
<body> 
<p th:text="${stduent.name}"></p> 
</body> 
</html> 

5. 通過Webjars引?靜態(tài)資源

Web前端使?了越來越多的JS或CSS,?般情況下,我們是將這些Web資源拷?到
Java的?錄下,或者通過CDN引?,通過??進?管理,這種?式容易導(dǎo)致?件混亂、
版本不?致等問題。
WebJars是將這些通?的Web前端資源打包成Java的Jar包,然后借助Maven?具對
其管理,保證這些Web資源版本唯?性,升級也?較容易。關(guān)于Webjars資源,有?個
專?的?站http://www.webjars.org/,我們可以到這個?站上找到??需要的資源,
在??的?程中添加?maven依賴,即可直接使?這些資源了。
如:?個使?bootstrap的Webjars的例?:

<html xmlns:th="http://www.thymeleaf.org"> 
<html lang="zh-CN"> 
<head> 
<meta charset="UTF-8"/> 
<title>歡迎頁面</title> 
<link rel="stylesheet"  href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" /> 
<body> 
<div class="alert alert-success"> 
<p th:text="${info}"></p> 
</div> 
</div> 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容