当前位置: 移动技术网 > IT编程>开发语言>Java > Thymeleaf常用语法:使用星号表达式

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

2019年10月19日  | 移动技术网IT编程  | 我要评论

拉拉,联系邮箱大全,妹妹最近有点怪

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

开发环境:intellij idea 2019.2.2
spring boot版本:2.1.8

新建一个名称为demo的spring boot项目。

1、pom.xml
加入thymeleaf依赖

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-thymeleaf</artifactid>
        </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<user> users = queryusers();
        model.addattribute("user", users.get(0));
        model.addattribute("users", users);
        return "test";
    }

    private list<user> queryusers(){
        list<user> users = new arraylist<user>();
        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>title</title>
    <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://www.lhsxpumps.com/_localhost:8080
显示如下截图所示:

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网