[JAVA EE] Thymeleaf 高级用法:模板布局,带参数的引用片段,表单验证,常用校验注解
模板布局
公共部分通常定義為模板布局:如頁眉,頁腳,公共導航欄、菜單等。
 
 模板布局定義方法
布局頁中用
th:fragment定義模板片段,其他頁面用th:insert引用片段
例如:footer.html,通過 th:fragment 定義一個模板片段
<footer th:fragment="copy">
…
</footer>
 
其他頁面通過 th:insert 引用片段:
- 標準形式:
 
<div th:insert = "~{ footer :: copy }"></div>
 
- 簡寫形式:
 
<div th:insert="footer :: copy"></div>
 
示例:(項目需要參考本人[JAVA EE]系列前文創(chuàng)建,請自行去本人主頁查閱)
- 在th文件夾下新建一個footer.html
 
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Footer</title></head><body><footer th:fragment="copy">? 2021 Hello Dust, here is your footer.</footer></body>
</html>
 
- 修改index.html
 
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Title</title></head><body><div th:insert="~{ th/footer::copy }"></div></body>
</html>
 
- 運行
 
th:insert 、th:replace、 th:include 區(qū)別
這三個運行結果表面看上去是相同的
 <div th:insert="~{ th/footer::copy }"></div>
 <div th:replace="~{ th/footer::copy }"></div>
 <div th:include="~{ th/footer::copy }"></div>
 
帶參數(shù)的引用片段
示例:
- footer.html
 
<footer th:fragment="copy(name)">? 2021 Hello Dust, here is your footer.<p th:text="'Authorized by ' + ${name}"></p>
</footer>
 
- index.html
 
<body><div th:insert="~{ th/footer::copy(${stuList[0].name}) }"></div>
</body>
 
- 附上我的控制器:
 - TestController.java
 
package com.example.demo.controller;import com.example.demo.bean.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Controller
public class TestController {@RequestMapping("/th")public String index(Model model) {List<Student> stuList = new ArrayList<Student>();stuList.add(new Student(2019001, "小明"));stuList.add(new Student(2019002, "小麗"));stuList.add(new Student(2019003, "小王"));model.addAttribute("stuList", stuList);return "th/index";}
}
 
- bean包里的student.java
 
package com.example.demo.bean;public class Student {private Integer id;  //學號private String name;  //姓名public Student() {}public Student(Integer id, String name) {this.id = id;this.name = name;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}
 
- 項目結構:
運行結果:
 - 在index.html里把[0]改成[1],就會變成:
 - 說明此處是傳參。
 
模板布局另一種定義方法:通過 id 屬性
- 創(chuàng)建html文件(如footer.html),直接通過 id 屬性定義一個片段
 
<footer id="copy">? 2021 Hello Dust, here is your footer.
</footer>
 
- 其他頁面通過 #id 引用片段(沒忘記#選擇器是id選擇器吧?)
 
<div th:insert="~{ footer :: #copy }"></div> 
 
表單驗證
表單輸入的信息通常需要進行驗證,以及提供錯誤信息反饋。
驗證相關的標簽
(1)單個字段錯誤信息提示:th:errors 標簽
<span th:if="${#fields.hasErrors('stu.name')}" th:errors="${stu.name}"></span>
 
#fields.hasErrors():指定字段是否有返回的錯誤信息
th:errors ():顯示指定字段返回來的錯誤信息
此例綁定的是stu.name屬性字段
(2)顯示所有錯誤信息:遍歷 #fields.errors()
<ul th:if="${#fields.hasErrors('stu.*')}"><li th:each="err:${#fields.errors('stu.*')}" th:text="${err}"></li>
</ul>
 
#fields.errors():獲取指定字段返回的錯誤信息
stu.*:表示stu對象的所有屬性字段
(1)添加驗證依賴,添加之后要重啟IDEA
- pom.xml
 
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
 
(2)在實體類屬性中添加約束
- Student.java
 
public class Student {@Min(value=2020001,message="最小值2020001")@Max(value=2020999,message="最大值2020999")private long id;//主鍵.@NotBlank(message="姓名不能為空")@Length(min=5,max=20,message="姓名長度為5-20個字符")private String name;…其他代碼不變
}
 
(3)添加控制器代碼
- TestController.java
 
@Controller
public class TestController {@RequestMapping("/th")public String index(Model model) {List<Student> stuList = new ArrayList<Student>();stuList.add(new Student(2019001, "小明"));stuList.add(new Student(2019002, "小麗"));stuList.add(new Student(2019003, "小王"));model.addAttribute("stuList", stuList);return "th/index";}@RequestMapping("/edit")public String edit( Model model){Student s=new Student(2019001,"小明");model.addAttribute("stu",s);return "th/form";}@RequestMapping(value="/save", method = RequestMethod.POST)public String save( @ModelAttribute("stu") @Validated Student stu,BindingResult bindingResult,Model model){if( bindingResult.hasErrors() ){return "th/form";}model.addAttribute("new_stu",stu);return "th/save"; //save.html略}}
 
- form.html
 
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>form</title><link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/><script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script><script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body><form th:action="@{/save}" method="post" th:object="${stu}"><div><label for="id">學號</label><input type="text" id="id" th:field="*{id}" placeholder="請輸入學號"><span th:if="${#fields.hasErrors('id')}" th:errors="*{id}" class="warn"></span></div><div><label for="name">姓名</label><input type="text" id="name" th:field="*{name}" placeholder="請輸入姓名"><span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="warn"></span></div><button id="btn" type="submit">保存</button><div><ul th:if="${#fields.hasErrors('*')}" class="warn"><li th:each="err:${#fields.errors('*')}" th:text="${err}" ></li></ul></div></form></body>
</html>
 
- 寫一個save.html,不然符合要求會報錯
 
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>Save</title></head><body><p>saved~</p></body>
</html>
 
- 運行結果:
 
常用校驗注解
| 注解 | 作用 | 
|---|---|
| @NotNull | 被注釋的元素必須不為 null | 
| @Min(value) | 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值 | 
| @Max(value) | 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值 | 
| @DecimalMin(value) | 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值 | 
| @DecimalMax(value) | 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值 | 
| @Pattern(value) | 被注釋的元素必須符合指定的正則表達式 | 
| 被注釋的元素必須是電子郵箱地址 | |
| @Length(min=, max=) | 被注釋的字符串的大小必須在指定的范圍內 | 
| @NotEmpty | 被注釋的字符串的必須非空 | 
| @Range(min=, max=) | 被注釋的元素必須在合適的范圍內 | 
| @NotBlank | 被注釋的字符串的必須非空 | 
| @URL(protocol=, host=, port=,regexp=, flags=) | 被注釋的字符串必須是一個有效的url | 
總結
以上是生活随笔為你收集整理的[JAVA EE] Thymeleaf 高级用法:模板布局,带参数的引用片段,表单验证,常用校验注解的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 日本清酒在中国卖多少钱一瓶?
 - 下一篇: 美国值多少钱啊?