Thymeleaf常用语法:使用星号表达式

在处理模板时,一般情况都是使用变量表达式 ${...} 来显示变量,还可以使用选定对象表达式 *{...},它也称为星号表达式。
如果在模板中先选定了对象,则需要使用星号表达式。Thymeleaf的内置对象#object效果等同于星号表达式。

开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一个名称为demo的Spring Boot项目。

1、pom.xml
加入Thymeleaf依赖

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>

2、src/main/java/com/example/demo/User.java

package com.example.demo;

public class User {
    Integer id;
    String name;

    public User(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;
    }
}

3、src/main/java/com/example/demo/TestController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class TestController {
    @RequestMapping("/")
    public String test(Model model){
        List users = queryUsers();
        model.addAttribute("user", users.get(0));
        model.addAttribute("users", users);
        return "test";
    }

    private List queryUsers(){
        List users = new ArrayList();
        users.add(new User(1,"张三"));
        users.add(new User(2,"李四"));
        users.add(new User(3,"王五"));
        return users;
    }
}

4、src/main/resources/templates/test.html 

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <style type="text/css">
        table { border-collapse:collapse;}
        td { border: 1px solid #C1DAD7;}
    style>
head>
<body>
    <div>使用变量表达式div>
    <table>
        <tr>
            <td th:text="${user.id}">td>
            <td th:text="${user.name}">td>
        tr>
    table>

    <div>使用星号表达式:使用星号div>
    <table>
        <tr th:object="${user}">
            <td th:text="*{id}">td>
            <td th:text="*{name}">td>
        tr>
    table>

    <div>使用星号表达式:使用#object对象div>
    <table>
        <tr th:object="${user}">
            <td th:text="${#object.id}">td>
            <td th:text="${#object.name}">td>
        tr>
    table>

    <div>在循环体中使用星号表达式div>
    <table>
        <tr th:each="u : ${users}" th:object="${u}">
            <td th:text="*{id}">td>
            <td th:text="*{name}">td>
        tr>
    table>


body>
html>

 

浏览器访问:http://localhost:8080
显示如下截图所示:

 Thymeleaf常用语法:使用星号表达式_第1张图片

 

你可能感兴趣的:(Thymeleaf常用语法:使用星号表达式)