小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Spring Boot :模版引擎 Thymeleaf 渲染 Web 頁(yè)面

 新用戶32269360 2020-06-10

Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 頁(yè)面


1. 什么是 Thymeleaf ?

雖然我們目前擁有許多十分優(yōu)秀的前端框架,例如: Vue 、 React 等,非常適用于前后端分離的場(chǎng)景,前端可以獨(dú)立部署成為服務(wù),前后端從物理上完全進(jìn)行隔離,降低程序耦合度。但是 Spring Boot 官方依然為我們提供了模版引擎用于一些無(wú)需前后端分離的場(chǎng)景。 Thymeleaf 是新一代的模板引擎,在 Spring Boot 中,官方推薦使用 Thymeleaf 來(lái)做前端模版引擎。打開(kāi) https://start./ 可以看到,在當(dāng)前Spring Boot 的版本中( 2.1.8.RELEASE ), 官方提供的模版引擎有以下幾種:

  • Thymeleaf

  • FreeMarker

  • Mustache

  • Groovy

Spring Boot 建議使用這些模版引擎,而并不推薦我們繼續(xù)使用 JSP 。

Thymeleaf 具體特性如下:(了解源碼可+求求: 1791743380)

  • Thymeleaf 在有網(wǎng)絡(luò)和無(wú)網(wǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁(yè)面的靜態(tài)效果,也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動(dòng)態(tài)頁(yè)面效果。這是由于它支持 html 原型,然后在 html 標(biāo)簽里增加額外的屬性來(lái)達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時(shí)會(huì)忽略未定義的標(biāo)簽屬性,所以 Thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁(yè)面時(shí),Thymeleaf 標(biāo)簽會(huì)動(dòng)態(tài)地替換掉靜態(tài)內(nèi)容,使頁(yè)面動(dòng)態(tài)顯示。

  • Thymeleaf 開(kāi)箱即用的特性。它提供標(biāo)準(zhǔn)和 Spring 標(biāo)準(zhǔn)兩種方言,可以直接套用模板實(shí)現(xiàn) JSTL、 OGNL表達(dá)式效果,避免每天套模板、改 Jstl、改標(biāo)簽的困擾。同時(shí)開(kāi)發(fā)人員也可以擴(kuò)展和創(chuàng)建自定義的方言。

  • Thymeleaf 提供 Spring 標(biāo)準(zhǔn)方言和一個(gè)與 SpringMVC 完美集成的可選模塊,可以快速的實(shí)現(xiàn)表單綁定、屬性編輯器、國(guó)際化等功能。

2. 快速入門(mén)

這里我們先正常構(gòu)建一個(gè) Spring Boot 工程: spring-boot-thymeleaf ,在 pom.xml 文件中引入 Thymeleaf 的相關(guān)依賴,如下:

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

工程的配置文件 application.yml 如下:

server:  port: 8080spring:  application:    name: spring-boot-thymleaf  thymeleaf:
    # 關(guān)閉thymeleaf緩存 開(kāi)發(fā)時(shí)使用 否則沒(méi)有實(shí)時(shí)畫(huà)面    cache: false
    # 檢查模板是否存在,然后再呈現(xiàn)    check-template-location: true
    # Content-Type value.    servlet:      content-type: text/html
    # 啟用MVC Thymeleaf視圖分辨率    enabled: true
    # Template encoding.    encoding: UTF-8
    # 關(guān)閉嚴(yán)格模式    mode: LEGACYHTML5
    # Prefix that gets prepended to view names when building a URL.    prefix: classpath:/templates/
    # Suffix that gets appended to view names when building a URL.    suffix: .html  mvc:
    # 指定靜態(tài)資源處理路徑    static-path-pattern: /static/**    view:      suffix: .htmlCOPY

有關(guān) thymeleaf 都寫(xiě)明了注釋,這里需要注意的有以下幾點(diǎn):

  • spring.thymeleaf.mode :這里是配置當(dāng)前模版的解析模式的,默認(rèn)值為 HTML ,這時(shí)會(huì)開(kāi)啟嚴(yán)格模式,所有的 HTML 必須有頭有尾,很多地方并不符合我們平時(shí)的書(shū)寫(xiě)習(xí)慣,這里最好關(guān)閉嚴(yán)格模式。

  • spring.thymeleaf.cache :這里是 thymeleaf 的緩存,在平時(shí)的練習(xí)中最好關(guān)閉,否則頁(yè)面修改后刷新瀏覽器將會(huì)無(wú)效,而在生產(chǎn)環(huán)境中,視具體的業(yè)務(wù)場(chǎng)景而定。

  • spring.mvc.static-path-pattern :這里是配置我們靜態(tài)資源的路徑,一般默認(rèn)是配置 /static/** 路徑,這里用于存放我們的 js 、 css 、圖片等靜態(tài)資源。

配置通用 404 和 500 頁(yè)面,直接在 templates\error 創(chuàng)建對(duì)應(yīng)頁(yè)面即可,這里可以看一下 Spring Boot 錯(cuò)誤頁(yè)面轉(zhuǎn)發(fā)的源碼 org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver,如下:

@Overridepublic ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
    ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);    if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
        modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
    }    return modelAndView;
}private ModelAndView resolve(String viewName, Map<String, Object> model) {
    String errorViewName = "error/" + viewName;
    TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,            this.applicationContext);    if (provider != null) {        return new ModelAndView(errorViewName, model);
    }    return resolveResource(errorViewName, model);
}COPY

可以看到這里會(huì)根據(jù)當(dāng)前的狀態(tài)響應(yīng)碼轉(zhuǎn)發(fā)到對(duì)應(yīng)的頁(yè)面,路由為 error/** 。筆者這里簡(jiǎn)單創(chuàng)建兩個(gè)錯(cuò)誤頁(yè)面,如圖:

Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 頁(yè)面

創(chuàng)建測(cè)試 Controller ,如下:

@Controllerpublic class HelloController {    @GetMapping("/hello")    public String hello(HttpServletRequest request) {        // 構(gòu)建測(cè)試數(shù)據(jù)
        Map<String, Object> map = new HashMap<>();

        UserModel userModel = new UserModel();
        userModel.setId(1L);
        userModel.setName("Spring Boot");
        userModel.setAge(18);

        map.put("user", userModel);

        List<CourseModel> list = new ArrayList<>();        for (int i = 0; i < 2; i++) {
            CourseModel courseMode = new CourseModel();
            courseMode.setId((long) i);
            courseMode.setName("Spring Boot:" + i);
            courseMode.setAddress("課程地點(diǎn):" + i);
            list.add(courseMode);
        }

        map.put("list", list);

        map.put("flag", true);

        request.setAttribute("data", map);        return "hello";
    }
}COPY

在此注冊(cè)測(cè)試類(lèi)中,進(jìn)行數(shù)據(jù)初始化并輸出至頁(yè)面。

  • Thymeleaf 默認(rèn)的模板路徑 src/main/resources/templates ,只需要在這個(gè)這個(gè)路徑下編寫(xiě)模版文件即可。

Thymeleaf 模版文件如下:

<!DOCTYPE html><html xmlns="http://www./1999/xhtml"
      xmlns:th="http://www."><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Hello Spring Boot</title>
    <link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}"></head><body><div class="container">
    <div>用戶信息:</div>
    <table class="table table-dark">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">姓名</th>
            <th scope="col">年齡</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <th scope="row" th:text="${data.user.id}"></th>
            <td th:text="${data.user.name}"></td>
            <td th:text="${data.user.age}"></td>
        </tr>
        </tbody>
    </table>
    <div>課程信息:</div>
    <table class="table table-dark">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">課程名稱</th>
            <th scope="col">課程地點(diǎn)</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="course, iterStat : ${data.list}">
            <th scope="row" th:text="${course.id}"></th>
            <td th:text="${course.name}"></td>
            <td th:text="${course.address}"></td>
        </tr>
        </tbody>
    </table>

    <div th:if="${data.flag == true}">如果 flag 為 true 你將可以看到這行字:)</div></div></body></html>COPY

Thymeleaf 部分常用 th 標(biāo)簽如下:

關(guān)鍵字功能介紹案例
th:id替換id<input th:id="'xxx' + ${collect.id}"/>
th:text文本替換<p th:text="${collect.description}">description</p>
th:utext支持html的文本替換<p th:utext="${htmlcontent}">conten</p>
th:object替換對(duì)象<div th:object="${session.user}">
th:value屬性賦值<input th:value="${user.name}" />
th:with變量賦值運(yùn)算<div th:with="isEven=${prodStat.count}%2==0"></div>
th:style設(shè)置樣式th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick點(diǎn)擊事件th:onclick="'getCollect()'"
th:each屬性賦值tr th:each="user,userStat:${users}">
th:if判斷條件<a th:if="${userId == collect.userId}" >
th:unless和th:if判斷相反<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href鏈接地址<a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch多路選擇 配合th:case 使用<div th:switch="${user.role}">
th:caseth:switch的一個(gè)分支<p th:case="'admin'">User is an administrator</p>
th:fragment布局標(biāo)簽,定義一個(gè)代碼片段,方便其它地方引用<div th:fragment="alert">
th:include布局標(biāo)簽,替換內(nèi)容到引入的文件<head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace布局標(biāo)簽,替換整個(gè)標(biāo)簽到引入的文件<div th:replace="fragments/header :: title"></div>
th:selectedselected選擇框 選中th:selected="(${xxx.id} == ${configObj.dd})"
th:src圖片類(lèi)地址引入<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline定義js腳本可以使用變量<script type="text/javascript" th:inline="javascript">
th:action表單提交的地址<form action="subscribe.html" th:action="@{/subscribe}">
th:remove刪除某個(gè)屬性<tr th:remove="all"> 1.all:刪除包含標(biāo)簽和所有的孩子。2.body:不包含標(biāo)記刪除,但刪除其所有的孩子。3.tag:包含標(biāo)記的刪除,但不刪除它的孩子。4.all-but-first:刪除所有包含標(biāo)簽的孩子,除了第一個(gè)。5.none:什么也不做。這個(gè)值是有用的動(dòng)態(tài)評(píng)估。
th:attr設(shè)置標(biāo)簽屬性,多個(gè)屬性可以用逗號(hào)分隔比如 th:attr="src=@{/image/aa.jpg},title=#{logo}" ,此標(biāo)簽不太優(yōu)雅,一般用的比較少。

3. 測(cè)試

啟動(dòng)當(dāng)前工程,打開(kāi)瀏覽器訪問(wèn)路徑: http://localhost:8080/hello ,結(jié)果如圖:

Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 頁(yè)面

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類(lèi)似文章 更多