首頁 Java java教程 SpringBoot+Thymeleaf基於HTML5現代模板引擎怎麼用

SpringBoot+Thymeleaf基於HTML5現代模板引擎怎麼用

May 15, 2023 pm 08:28 PM
html5 springboot thymeleaf

開始使用

1.引入依賴

#SpringBoot預設提供了Thymeleaf的Starter,只需簡單引入依賴即可。

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

目前預設版本是2.1,如果想升級版本到3.0,可以這樣修改。

  <properties>
    <thymeleaf.version>3.0.7.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
  </properties>

為了方便開發,專案案例採用了熱部署工具dev-tools ,這樣我們在修改頁面之後,IDEA會自動加載,從而達到實現熱更新的效果。

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
    </dependency>

註:由於IDEA預設關閉了熱部署,需要做一些設定才能使其生效。解決方法:先按住Ctrl Shift Alt / 然後進入 Registry ,然後勾選compiler.automake.allow.when.app.running 即可。另外,Build->Compiler 也要勾選上Build Project automatically .

2. 新增相關配置

Thymeleaf預設開啟了頁面緩存,在開發的時候,應該要關閉快取。此外,通常我們也會指定頁面的存放路徑。 (預設是classpath:/templates/)

application.yml 配置如下:
spring:
 thymeleaf:
  cache: false #关闭缓存
  prefix: classpath:/views/ #添加路径前缀

3.寫HTML

寫Thymeleaf和書寫HTML5頁面沒有什麼不同,最大的轉變就是使用拓展屬性( th:xx)去跟服務端進行資料交互,保留原始頁面風格,也是Thymeleaf的推崇的風格。例如下面這個簡單的案例,啟動項目,我們發現頁面跳轉的是簡書的連接,這一點也驗證了Thymeleaf覆蓋原生頁面數據的極佳能力。

頁碼:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Thymeleaf</title>
</head>
<body>
  <h3>欢迎使用Thymeleaf!!</h3>
  <a href="http://www.baidu.com" rel="external nofollow" th:href="${info}" rel="external nofollow" >戳我有惊喜</a>
</body>
</html>

後端程式碼:

@Controller
public class UserController {

  @GetMapping("/")
  public String index(Model model) {
    model.addAttribute("info", "user/list");
    return "index";
  }

  @GetMapping("/user")
  public String hehe(Model model) {
    model.addAttribute("user", new User(UUID.randomUUID().toString(), "yizhiwazi", "20170928"));
    return "user";
  }

  @GetMapping("/user/list")
  public String userlist(Model model) {
    List<User> userList = new ArrayList<>();
    userList.add(new User(UUID.randomUUID().toString(), "yizhiwazi", "20170928"));
    userList.add(new User(UUID.randomUUID().toString(), "kumamon", "123456"));
    userList.add(new User(UUID.randomUUID().toString(), "admin", "admin"));
    model.addAttribute("userList", userList);
    return "userList";
  }

}

現在我們嘗試回填一個表單,展示單一使用者資訊。

<!-- 使用th:object 搭配*{} 可以省略对象名 -->
<form action="/" th:object="${user}" >
  <input type="hidden" name="userId" th:value="*{userId}" />
  <input type="text" name="username" th:value="*{username}" />
  <input type="text" name="password" th:value="*{password}" />
</form>

接下來,我們進入一個更複雜的案例,例如展示一個用戶列表信息,不需要編寫新的標籤,就可以完成對批量用戶的遍歷。

<h3>用户列表</h3>
<!--说明: th:each="obj,stat:${objects}" 分别代表单个实例,状态(可省略),待遍历对象-->
<div th:each="user:${userList}">
  <input type="hidden" name="userId" th:value="${user.userId}"/>
  用户姓名:<input type="text" name="password" th:value="${user.username}"/>
  登录密码:<input type="text" name="username" th:value="${user.password}"/>
</div>

以上是SpringBoot+Thymeleaf基於HTML5現代模板引擎怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

如何在HTML5中使用服務器量事件(SSE)? 如何在HTML5中使用服務器量事件(SSE)? Sep 21, 2025 am 06:11 AM

SSEenablesreal-time,unidirectionalserver-to-clientupdatesviaHTTP;useEventSourceinJavaScripttoconnect,handlemessageswithonmessage,setserverresponsetypetotext/event-stream,formatdatawith"data:"and"\n\n",andoptionallyincludeeventIDsf

如何管理HTML5中可訪問性的焦點? 如何管理HTML5中可訪問性的焦點? Sep 21, 2025 am 05:27 AM

UsesemanticHTMLelementslikeandfornativefocusabilityandkeyboardsupport.EnsurelogicaltaborderandvisiblefocusindicatorsviaCSS.Programmaticallymanagefocusindynamiccontentlikemodalsusingelement.focus(),trappingfocusinsideandreturningitafterclosure.ApplyAR

如何使用ARIA角色在HTML5中可訪問? 如何使用ARIA角色在HTML5中可訪問? Sep 21, 2025 am 04:41 AM

ARIAenhanceswebaccessibilitybyaddingsemanticmeaningtoelementswhennativeHTMLisinsufficient.UseARIAroleslikerole="button",aria-expanded,andaria-labelforcustomcomponentsordynamiccontent,butalwaysprefernativeHTMLelementssuchasbuttonornav.Update

如何根據HTML5中的正則表達式驗證形式場? 如何根據HTML5中的正則表達式驗證形式場? Sep 22, 2025 am 05:11 AM

UsEthepatternattributeInhtml5InputElementStavalIdateAgainStareGex,SustAsForpassWordsRequiringNumbers,大寫,小寫,小寫和最小值; pairwithTitleForuserGuuserGuiDanceNanceNanceAgeAgeAgeAncuiredeNandAnceAndEnceAneandRequiredFornonOn-enon-emptement-emptentement-emptentement。

如何在HTML5表單中使用佔位符屬性? 如何在HTML5表單中使用佔位符屬性? Sep 23, 2025 am 05:17 AM

placeholderaterattributrovidesashorthintininputfields.itappearsfaintlyanddisappearspearspearspearspearpebebebebebebebebegins,supportEdIntext,電子郵件,tel,tel,search,andtextareAlements.useittoshowexamplease.useittoshowexampleslike example@email@email@email.com,butnotasareplacementforlacementforlabels.labelsensurebelsen.labelsensureb.labelserureb

如何在HTML5文檔中對SVG路徑進行動畫動畫? 如何在HTML5文檔中對SVG路徑進行動畫動畫? Sep 21, 2025 am 01:58 AM

USECSSSTROKE-DASHARRAYAND和Strows-DashoffSetForsimpledrawingAnimations; 2.ApplyJavascriptForderynamicTriggerSlikeloadorsCroll; 3. 3. EmploylibrariesLibrariesLiblarieLikeGsapForPathMorphring; 4.4.ptimizeptimizeperanceBylimizeperanceBylimityBylimityConconcurrentanimations。

如何構建HTML5頁面? 如何構建HTML5頁面? Sep 20, 2025 am 04:03 AM

AWELL結構的HTML5PAGESTARTSWITHAND,隨後的byAsectionContaining,fiewportSettings,title和andcsslinks,thenawithsemanticelementslike,,,,,,, and forclearlayout,可訪問性和訪問性。

如何將所需屬性用於HTML5中的表單字段? 如何將所需屬性用於HTML5中的表單字段? Sep 24, 2025 am 02:56 AM

thequiredattributeinhtml5ensuresformfordsarefillebeforeSubmission,supportedbyInputTypyTypeslikeText,電子郵件,密碼,複選框,無線電,select,select和file;

See all articles