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

Springboot詳解如何整合使用Thymeleaf

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

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

如果我們沒有模板引擎的話,在頁面中會提示500

引入Thymeleaf

在項目中加入依賴

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

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

Thymeleaf 在Github 的主頁:https://github.com/thymeleaf/thymeleaf

Spring官方文檔:找到我們對應的版本

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

我們可以有通過上述的頁面找到我們需要的依賴,進而復制粘貼即可。

引入之后我們再次運行。nice

注意: 使用Thymeleaf,只需要導入對應的依賴即可。同時我們的html頁面試放在我們的templates目錄下的。

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

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

取值

那么我們應該怎么取值呢

首先在controller下編寫代碼

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

接下來我們在html頁面中編寫

因為我們要使用thymeleaf,需要在html文件中導入命名空間的約束。

<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>

成功運行后

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

有無轉義

從controller傳一段信息

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

html中使用轉義和不轉義的情況

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

運行結果

循環(huán)

同樣在controller里傳一段信息

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

接下來在html中進行取值

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

運行結果

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

相關文章

最新評論