spring boot使用thymeleaf為模板的基本步驟介紹,springthymeleaf

來源:互聯網
上載者:User

spring boot使用thymeleaf為模板的基本步驟介紹,springthymeleaf

前言

在開發過程中,使用模板引擎是很有必要的。jsp已經明顯跟不上時代發展了,freemarker用的夠夠的?換thymeleaf試試吧。

springboot官方推薦的是freemarker和thymeleaf,而thymeleaf相對於freemarker更讓人感覺強大的,是他可以動態替換標籤內靜態內容,這樣前端可以安心寫頁面,後台可以安心擼介面,只需要把變數替換一下即可,這種理念,不知道是VUE抄襲了thymeleaf還是thymeleaf抄襲了VUE,不過無所謂了 ,對於我們廣大碼奴來說,實用就好。

經過查閱資料,配置好後,現在將實現的過程分享給大家,下面話不多說了,來一起看看詳細的介紹吧。

壹、pom引入

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

貳、application.properties添加thymeleaf配置

spring.thymeleaf.cache=falsespring.thymeleaf.check-template=truespring.thymeleaf.check-template-location=truespring.thymeleaf.content-type=text/htmlspring.thymeleaf.enabled=truespring.thymeleaf.encoding=utf-8spring.thymeleaf.mode=HTML5spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.html

三、編寫html

<!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org"><head> <title>demo</title></head><body><p>這是第一段</p><p th:text="${textValue}">這是第二段</p></body></html>

肆、測試類別

package com.mos.easyboot.admin.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("demo")public class DemoController { @RequestMapping("index") public String index(Model model){ String textValue = "上士聞道,僅能行之;中士聞道,若存若亡;下士聞道,大笑之。" +  "不笑不足以為道。" +  "故建言有之:明道若昧;進道若退;夷道若纇(lei);上德若穀,大白若辱,廣德若不足,建德若偷,質真若渝;大方無隅;大器免成;大音希聲;大象無形。" +  "道隱無名。" +  "夫唯道,善始且善成。"; model.addAttribute("textValue",textValue); return "demo/demo"; }}

伍、頁面效果

陸、資料渲染

VUE有個SSR(服務端渲染)的問題比較頭疼,雖然也有解決方案(見我之前寫的文章《 前後端分離Nuxt.js解決SEO問題 》),但總覺得還是讓適合的技術做時候的業務比較好,而thymeleaf還是相當於在服務端渲染,查看頁面源碼如下:

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對幫客之家的支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.