一、基本介紹
Thymeleaf是一個模板引擎。它的主要目的是為Web和獨立環境創建HTML、XML、JavaScript、CSS和文本輸出。它是在Java平台上執行的,但它的語法從未與Java平台交叉。Thymeleaf與Spring框架緊密集成,因此它在Spring MVC應用程序中的使用非常廣泛。在Thymeleaf中,th:field是一個支持雙向綁定的屬性,它允許將表單字段與一個對象的屬性相關聯。
二、th:field與表單輸入
Thymeleaf中的表單輸入受到th:field屬性的支持。在使用此屬性時,可以將表單的值與後台對象綁定,以便在表單提交時可以自動填充對象屬性。下面是一個示例,展示了如何使用th:field將表單與對象的屬性綁定:
<form th:object="${user}"> <!-- 綁定<input>元素與後台對象的firstName屬性 --> <input type="text" th:field="*{firstName}" /> <!-- 綁定<input>元素與後台對象的lastName屬性 --> <input type="text" th:field="*{lastName}" /> </form>
在這個例子中,表單中的輸入框被用th:field綁定到了user對象的屬性上。*{firstName} 和 *{lastName},它們代表了一個Spring MVC表單的空間綁定表達式,指定了綁定到模型對象的後面,在這種情況下是user對象的屬性。這意味着,當用戶提交表單時,表單值會自動填充到user的firstName和lastName屬性中。
三、屬性綁定的數據類型轉換
Thymeleaf通過使用屬性編輯器處理類型轉換。屬性編輯器是一個將表單中輸入的字符串轉換為對象屬性類型的類。例如,當將一個字符串轉換為Integer類型時,類似「12」或「45.6」這樣的字符不能轉換為整數。為了解決這個問題,Thymeleaf支持自定義屬性編輯器來解決類型轉換:
/** * 將字符串轉換為ZonedDateTime類型 */ public class ZonedDateTimeEditor extends PropertyEditorSupport { @Override public void setAsText(String text) { // 日期字符串轉成DateTime類型 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); ZonedDateTime dateTime = ZonedDateTime.parse(text, formatter.withZone(ZoneId.systemDefault())); setValue(dateTime); } }
在上述代碼中,我們使用ZonedDateTimeEditor屬性編輯器將字符串轉換為ZonedDateTime類型,ZonedDateTime是Java8中處理帶時區的日期和時間的類。我們重寫了PropertyEditorSupport中的setAsText方法來執行字符串到ZonedDateTime類型的轉換。一旦我們有了這個編輯器類,就可以將它註冊到Thymeleaf中:
@Configuration public class AppConfig { @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine engine = new SpringTemplateEngine(); // 使用thymeleaf的方言 Set dialects = new HashSet(); dialects.add(new SpringStandardDialect()); dialects.add(new LayoutDialect()); engine.setAdditionalDialects(dialects); // 註冊屬性編輯器 Set formatters = new HashSet(); formatters.add(new ZonedDateTimeFormatter()); engine.setAdditionalFormatters(formatters); return engine; } }
在這個例子中,我們將自定義屬性編輯器註冊到Thymeleaf中,然後將它們配置為SpringTemplateEngine的一個附加組件。這使得Thymeleaf能夠找到這些類型轉換程序,並在需要時使用它們。因此,這將允許Thymeleaf將輸入字符串轉換為我們需要的類型,例如ZonedDateTime。
四、表單驗證
在表單中,為了提供更好的用戶體驗和錯誤預防機制,表單驗證是必不可少的。Thymeleaf為表單驗證提供了多個選項,其中之一是使用EasyValidation框架進行表單驗證。
1. 添加EasyValidation依賴
首先,您需要將EasyValidation添加到您的項目中,在pom.xml中添加以下依賴項:
<dependency> <groupId>de.ahus1</groupId> <artifactId>easy-validation</artifactId> <version>2.0.0-SNAPSHOT</version> </dependency>
2. 定義驗證規則
在添加EasyValidation依賴項之後,我們需要定義要在表單上執行的驗證規則。下面是一個規則定義的示例:
public class UserValidation extends Validator implements Serializable { private static final long serialVersionUID = 1L; @Override protected void configure() { super.configure(); //檢測年齡是否為空,是否在18-65之間 constraintFor(User.class, "age") .notEmpty() .minValue(18) .maxValue(65); //檢測名字是否為空 constraintFor(User.class, "name").notEmpty(); //驗證郵件地址是否合法 constraintFor(User.class, "email").emailAddress(); } }
在這個例子中,我們定義了UserValidation類型來執行表單驗證。這個驗證器與一個User類型相關聯。 我們定義了三項約束:age屬性不能為空,必須大於18個月小於65年,name屬性不能為空,email屬性必須是一個有效的電子郵件地址。
3. 將約束綁定到表單
一旦我們定義了驗證規則,我們需要將它們綁定到表單上。下面是一個模板示例,在視圖中綁定驗證約束:
<form th:object="${user}" th:validate="${userValidation}" > <label>Age:</label> <input type="number" th:field="*{age}" /> <small th:errors="*{age}">Age error message</small> <label>Name:</label> <input type="text" th:field="*{name}" /> <small th:errors="*{name}">Name error message</small> <label>Email:</label> <input type="email" th:field="*{email}" /> <small th:errors="*{email}">Email error message</small> </form>
在這個例子中,我們使用th:validate將UserValidation對象綁定到的表單上。現在,一個表單字段具有th:field屬性,它綁定到我們的User對象的屬性上。當表單提交時,如果任何約束失敗,那麼EasyValidation將向同一字段添加一個錯誤消息。使用th:errors指令可以在表單字段的下方添加錯誤消息。
五、使用Bootstrap樣式
在Web應用程序中,使用漂亮的樣式能大大提高用戶體驗。Bootstrap是一個強大的CSS框架,它為表單提供了很好的樣式。在Thymeleaf中使用Bootstrap can是非常簡單的。
1. 添加Bootstrap依賴
首先,您需要將Bootstrap添加到您的項目中,在pom.xml中添加以下依賴項:
<dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.3.1</version> </dependency>
2. 鏈接Bootstrap樣式表
添加了Bootstrap依賴項後,需要向HTML頁面添加Bootstrap樣式表。這可以通過在標記的底部添加以下代碼實現:
<link href="webjars/bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet">
3. 使用Bootstrap樣式的表單
一旦您準備好包含Bootstrap樣式,您可以建立一個使用Bootstrap樣式的表單。下面是一個表單示例:
<form th:object="${user}" th:validate="${userValidation}"> <div class="form-group"> <input type="text" th:field="*{name}" class="form-control" placeholder="Name"> <small th:errors="*{name}" class="form-text text-danger"></small> </div> <div class="form-group"> <input type="email" th:field="*{email}" class="form-control" placeholder="Email"> <small th:errors="*{email}" class="form-text text-danger"></small> </div> <div class="form-group"> <label>Birthday:</label> <input type="date" th:field="*{birthday}" class="form-control" placeholder="Birthday"> <small th:errors="*{birthday}" class="form-text text-danger"></small> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>
在這個例子中,我們使用Bootstrap樣式來改善表單的外觀並增加響應性。
原創文章,作者:MTYGJ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/331584.html