欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot詳解如何整合使用Thymeleaf

 更新時(shí)間:2022年06月28日 09:02:58   作者:奔走的王木木Sir  
這篇文章主要分享了Spring Boot整合使用Thymeleaf,Thymeleaf是新一代的Java模板引擎,類似于Velocity、FreeMarker等傳統(tǒng)引擎,關(guān)于其更多相關(guān)內(nèi)容,需要的小伙伴可以參考一下

模板引擎的作用就是我們來寫一個(gè)頁(yè)面模板,比如有些值呢,是動(dòng)態(tài)的,我們寫一些表達(dá)式。而這些值,從哪來呢,就是我們?cè)诤笈_(tái)封裝一些數(shù)據(jù)。然后把這個(gè)模板和這個(gè)數(shù)據(jù)交給我們模板引擎,模板引擎按照我們這個(gè)數(shù)據(jù)幫你把這表達(dá)式解析、填充到我們指定的位置,然后把這個(gè)數(shù)據(jù)最終生成一個(gè)我們想要的內(nèi)容給我們寫出去,這就是我們這個(gè)模板引擎

如果我們沒有模板引擎的話,在頁(yè)面中會(huì)提示500

引入Thymeleaf

在項(xiàng)目中加入依賴

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Thymeleaf 官網(wǎng):https://www.thymeleaf.org/

Thymeleaf 在Github 的主頁(yè):https://github.com/thymeleaf/thymeleaf

Spring官方文檔:找到我們對(duì)應(yīng)的版本

https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/htmlsingle/#using-boot-starter

我們可以有通過上述的頁(yè)面找到我們需要的依賴,進(jìn)而復(fù)制粘貼即可。

引入之后我們?cè)俅芜\(yùn)行。nice

注意: 使用Thymeleaf,只需要導(dǎo)入對(duì)應(yīng)的依賴即可。同時(shí)我們的html頁(yè)面試放在我們的templates目錄下的。

至于為什么,我們看源碼,這段源碼在ThymeleafProperties下。

private String prefix = "classpath:/templates/";
private String suffix = ".html";

取值

那么我們應(yīng)該怎么取值呢

首先在controller下編寫代碼

@Controller
public class HelloController {
    @RequestMapping("/test")
    public String hello(Model model){
        model.addAttribute("msg","王木木");
        return "test";
    }
}

接下來我們?cè)趆tml頁(yè)面中編寫

因?yàn)槲覀円褂胻hymeleaf,需要在html文件中導(dǎo)入命名空間的約束。

<html lang="en" xmlns:th="http://www/thymeleaf.org">
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>

成功運(yùn)行后

這里需要這個(gè)的th標(biāo)簽。所有的html元素都科一被thymeleaf替換接管,格式為th:元素名

有無轉(zhuǎn)義

從controller傳一段信息

model.addAttribute("msg","<h1>王木木</h1>");

html中使用轉(zhuǎn)義和不轉(zhuǎn)義的情況

<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>

運(yùn)行結(jié)果

循環(huán)

同樣在controller里傳一段信息

model.addAttribute("users", Arrays.asList("wangmumu","王木木"));

接下來在html中進(jìn)行取值

<h2 th:each="user:${users}" th:text="${user}"></h2>

運(yùn)行結(jié)果

到此這篇關(guān)于Springboot詳解如何整合使用Thymeleaf的文章就介紹到這了,更多相關(guān)Springboot Thymeleaf內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論