乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Spring Boot :模版引擎 Thymeleaf 渲染 Web 頁面

       新用戶32269360 2020-06-10

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


      1. 什么是 Thymeleaf ?

      雖然我們目前擁有許多十分優(yōu)秀的前端框架,例如: Vue 、 React 等,非常適用于前后端分離的場景,前端可以獨(dú)立部署成為服務(wù),前后端從物理上完全進(jìn)行隔離,降低程序耦合度。但是 Spring Boot 官方依然為我們提供了模版引擎用于一些無需前后端分離的場景。 Thymeleaf 是新一代的模板引擎,在 Spring Boot 中,官方推薦使用 Thymeleaf 來做前端模版引擎。打開 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ǎng)絡(luò)的環(huán)境下皆可運(yùn)行,即它可以讓美工在瀏覽器查看頁面的靜態(tài)效果,也可以讓程序員在服務(wù)器查看帶數(shù)據(jù)的動態(tài)頁面效果。這是由于它支持 html 原型,然后在 html 標(biāo)簽里增加額外的屬性來達(dá)到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時(shí)會忽略未定義的標(biāo)簽屬性,所以 Thymeleaf 的模板可以靜態(tài)地運(yùn)行;當(dāng)有數(shù)據(jù)返回到頁面時(shí),Thymeleaf 標(biāo)簽會動態(tài)地替換掉靜態(tài)內(nèi)容,使頁面動態(tài)顯示。

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

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

      2. 快速入門

      這里我們先正常構(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緩存 開發(fā)時(shí)使用 否則沒有實(shí)時(shí)畫面    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 都寫明了注釋,這里需要注意的有以下幾點(diǎn):

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

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

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

      配置通用 404 和 500 頁面,直接在 templates\error 創(chuàng)建對應(yīng)頁面即可,這里可以看一下 Spring Boot 錯(cuò)誤頁面轉(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

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

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

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

      @Controllerpublic class HelloController {    @GetMapping("/hello")    public String hello(HttpServletRequest request) {        // 構(gòu)建測試數(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

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

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

      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替換對象<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圖片類地址引入<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è)值是有用的動態(tài)評估。
      th:attr設(shè)置標(biāo)簽屬性,多個(gè)屬性可以用逗號分隔比如 th:attr="src=@{/image/aa.jpg},title=#{logo}" ,此標(biāo)簽不太優(yōu)雅,一般用的比較少。

      3. 測試

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

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

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

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多