App下載

教你使用Java中的Thymeleaf類 附實(shí)例代碼

著名奶茶鑒定家 2021-08-20 11:46:30 瀏覽數(shù) (2096)
反饋

說(shuō)起Java的Thymeleaf類,相信很多的小伙伴們對(duì)此都非常的陌生。Thymeleaf類作為Java中一個(gè)xml、xhtml以及html5的模板引擎的類庫(kù),可以作為mvc的web應(yīng)用的view層。下面分享一下關(guān)于Java的Thymeleaf類庫(kù)的實(shí)例代碼應(yīng)用。

Java代碼

package com.zzx.controller;

import com.zzx.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;

/**
 * @date: 2021/04/25/ 10:07
 * @author: ZhengZiXuan
 * @description: 由于Spring Boot 不推薦我們使用.jsp,所以我們就使用html配合thymeleaf來(lái)進(jìn)行數(shù)據(jù)的傳輸
 * @title: Thymeleaf簡(jiǎn)單使用
 */
@Controller
@RequestMapping("/thyme")
public class ThymeleafController {

    @RequestMapping("data")
    public String ShowData(Model model){
        model.addAttribute("text","<a href='#'>點(diǎn)擊1</a>");
        model.addAttribute("utext","<a href='#'>點(diǎn)擊1</a>");
        model.addAttribute("value","input值");
        model.addAttribute("user",new User(1,"張三"));
        model.addAttribute("num",100);
        model.addAttribute("flag",true);
        model.addAttribute("list", Arrays.asList("Java","WEB","UI"));
        return "data";
    }
}    

前端代碼

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--此處需要配置thymeleaf,可以不配置,但是會(huì)爆紅,不會(huì)影響最終效果-->
<head>
    <meta charset="UTF-8">
    <title>thymeleaf的簡(jiǎn)單使用</title>
</head>
<body>

<!--取出后的值,填充到p標(biāo)簽中間,將字符串的標(biāo)簽解析字符串-->
<p th:text="${text}"></p><br/><hr>

<!--取出后的值,填充到p標(biāo)簽中間,utext會(huì)將字符串的標(biāo)簽解析為html標(biāo)簽-->
<p th:text="${utext}"></p><br/>

<!--th:value,相當(dāng)于是給原value屬性賦值-->
<input th:value="${value}"/><br/><hr/>

<!--thymeleaf支持屬性導(dǎo)航, 對(duì)象.屬性-->
id:<p th:text="${user.id}"></p><br>
name:<p th:text="${user.name}"></p><br>
<br><hr/>
<p th:text="${num}"></p>
<br/><hr/>

<!--th:if 判斷,如果判斷成功,該標(biāo)簽內(nèi)的內(nèi)容會(huì)展示,否則不展示-->
<p th:if="${flag}== true">
    看這里看這里
</p>
<hr>
<ol>
    <!--th:each 變量
        1. th:each 屬性在哪個(gè)標(biāo)簽,哪個(gè)標(biāo)簽循環(huán)出現(xiàn)
        2. th:each= "遍歷得到結(jié)果變量 :${key}"
        3. 在當(dāng)前標(biāo)簽,或者內(nèi)部標(biāo)簽就可以使用"遍歷得到結(jié)果變量"
    -->
    <li th:text="${str}" th:each="str : ${list}"></li>
</ol>
</body>
</html>

最終效果

20210428114330111

到此這篇關(guān)于Java中的Thymeleaf類庫(kù)的簡(jiǎn)單使用的文章就介紹到這了,更多相關(guān)Java其他類庫(kù)使用的內(nèi)容請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,也希望大家以后多多支持我們!


0 人點(diǎn)贊