本文章將介紹Thymeleaf標準表示式語法中的概念。
Product
類的bean已經設定為名稱為product
的上下文模型。Integer
和Date
屬性新增一些格式,學習使用#dates
和#numbers
實用程式物件的定義。如果要上機實踐,請參考:Thymeleaf+SpringMVC5範例專案。這裡不再重複建立專案的過程,這裡將只介紹如何使用Thymeleaf
標準表示式和標籤。
這裡建立一個Maven Web專案: thymeleaf-tutorials ,其目錄結構如下所示 -
Bean類的實現:Product.java -
package com.yiibai.spring.bean;
import java.util.Date;
public class Product {
private String description;
private Integer price;
private Date availableFrom;
public Product(final String description, final Integer price, final Date availableFrom) {
this.description = description;
this.price = price;
this.availableFrom = availableFrom;
}
public Date getAvailableFrom() {
return this.availableFrom;
}
public void setAvailableFrom(final Date availableFrom) {
this.availableFrom = availableFrom;
}
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
public Integer getPrice() {
return this.price;
}
public void setPrice(final Integer price) {
this.price = price;
}
}
控制器類的實現:MyController.java -
package com.yiibai.spring.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.yiibai.spring.bean.Product;
@Controller
public class MyController {
@GetMapping("/")
public String index(Model model) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Product product = new Product("花生油", 129, sdf.parse("2018-02-18"));
model.addAttribute("product", product);
return "index";
}
}
模板檔案的實現:/webapp/WEB-INFO/views/index.html -
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>SpringMVC5+Thymeleaf範例</title>
</head>
<body>
<h2>Spring MVC5 + Thymeleaf物件屬性格式化輸出</h2>
<h2>產品資訊</h2>
<dl>
<dt>產品名稱:</dt>
<dd th:text="${product.description}">葡萄乾</dd>
<dt>產品價格:</dt>
<dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">350</dd>
<dt>產品有效時間:</dt>
<dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">28-Jun-2018</dd>
</dl>
</body>
</html>
執行上面專案,在瀏覽器中顯示效果如下 -