SpringBoot+Thymeleaf實現數據渲染

Thymeleaf簡介

1.是什麼

Thymeleaf是spring boot推薦使用的模板語法,它可以完全替代 JSP 。
從代碼層次上講:Thymeleaf是一個java類庫,它是一個xml/xhtml/html5的模板引擎,可以作爲mvc的web應用的view層。

2.優點

開箱即用,它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、改jstl、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言;
Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。
有網無網的情況下模版頁面都可以執行,美工的頁面拿來就可以用,相對jsp減少了額外的標籤,頁面也更加簡潔。

3.常用標籤

屬性 作用 優先級(數字越小,優先級越高)
th:text 設置當前元素的文本內容 7
th:value 設置當前元素的value值,類似修改指定html標籤屬性的還有th:src,th:href 6
th:each 遍歷循環元素,和th:text或th:value一起使用 2
th:if 條件判斷 3

4.標準表達式語法

語法 含義
${…} 變量表達式(最常用)
@{…} 鏈接表達式
#{…} 消息表達式
~{…} 代碼塊表達式
*{…} 選擇變量表達式

SpringBoot+Thymeleaf交互

1.交互代碼

在controller中綁定數據,並將數據返回到指定頁面


@Controller
@RequestMapping("/mapImage/mapImage")
public class MapImageController extends BaseController
{
    private String prefix = "mapImage/mapImage";

    @Autowired
    private MapImageController Service MzMapImageService;

    @Autowired
    private CommunitymanageService CommunitymanageService;
    
    @GetMapping()
    @ApiOperation("查詢社區")
    public String mapImage(ModelMap model)
    {
        List<Communitymanage> list = CommunitymanageService.queryCommunityInfo();
        model.put("list", list);
        return prefix + "/mapImage";
    }
}

在mapImage.html頁面中,通過thymeleaf的語法將數據渲染

<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<div>
	<p class="contentTitle">社區信息</p>
	<p th:each="list:${list}" th:text="${list.communityname}")></p>
</div>

2.關鍵代碼解析

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章