網頁

2021/5/23

Spring Boot Thymeleaf 選擇物件表示式(星號語法)*{...} expressions on selections (asterisk syntax)

Spring Boot Thymeleaf 星號語法*{...}用法如下。


參考「Spring Boot + Thymeleaf 簡單範例」搭建好Spring Boot Thymeleaf專案,下面依此進行修改。


*{...}作用和${...}用法類似皆用來從環境中取得變數,差別在於*{...}在有th:object選定物件的情況下只會取得該物件的屬性。

建立一個Employee類,此物件的屬性將在hello.html中以${...}*{...}取得。

Employee

package com.abc.demo.model;

public class Employee {

    private long id;
    private String name;
    private int age;

    // getters and setters
}

在導向hello.htmlDemoController.hello()建立Employee物件並設為model attribute名稱為"employee"。

DemoController

package com.abc.demo.controller;

import com.abc.demo.model.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DemoController {

    @GetMapping("/hello")
    public String hello(
            @RequestParam(name = "name", required = false, defaultValue = "World") String name,
            Model model) {
        model.addAttribute("name", name); // set request attribute

        Employee employee = new Employee();
        employee.setId(1);
        employee.setName("John");
        employee.setAge(29);
        
        model.addAttribute("employee", employee);

        return "hello"; // forward to hello.html
    }
}

在thymeleaf模板hello.html使用${...}*{...}取得Employee的屬性。在<div>使用th:object="${employee}"獲取"employee"的物件,所以子標籤<li>*{id}相當於${employee.id}。此即為星號語法的效果。

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Hello Thymeleaf</title>
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'"/>

    <h3>Employee</h3>
    <div th:object="${employee}">
        <ul>
            <li>ID:<span th:text="*{id}"></span></li> <!-- 相當於${emloyee.id} -->
            <li>Name:<span th:text="${employee.name}"></span></li>
            <li>Age:<span th:text="${#object.age}"></span></li>
        </ul>
    </div>

</body>
</html>

啟動專案在瀏覽器輸入http://localhost:8080/demo/hello顯示結果如下。




參考github


沒有留言:

張貼留言