Thymeleaf简单格式化输出

本文章将介绍Thymeleaf标准表达式语法中的概念。

  • 学习如何在Thymeleaf模板中显示对象(Bean)的属性值。
  • 已经将Product类的bean已经设置为名称为product的上下文模型。
  • 为这些IntegerDate属性添加一些格式,学习使用#dates#numbers实用程序对象的定义。
  • 最后,修改模板以获得一个合理的静态原型(例如,通过一些原型数据替换并显示结果)。

如果要上机实践,请参考:Thymeleaf+SpringMVC5示例项目。这里不再重复创建项目的过程,这里将只介绍如何使用Thymeleaf标准表达式和标签。

这里创建一个Maven Web项目: thymeleaf-tutorials ,其目录结构如下所示 -

Bean类的实现:Product.java -

package com.voidme.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.voidme.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.voidme.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>

运行上面项目,在浏览器中显示效果如下 -