Thymeleaf变量表达式

x33g5p2x  于2022-10-11 转载在 其他  
字(2.8k)|赞(0)|评价(0)|浏览(486)

在本教程中,我们将通过一个示例学习Thymeleaf变量表达式
在Thymeleaf教程中查看完整的Thymelaaf教程和示例
变量表达式是Thymeleaf模板中最常用的表达式。这些表达式有助于将模板上下文(模型)中的数据绑定到结果HTML(视图)中

语法:

${变量名称}
考虑到我们已经在Spring MVC控制器中向模型添加了数据,为了访问模型数据,我们使用了Thymeleaf变量表达式

变量表达式示例

让我们使用spring initializr创建一个Spring启动项目,并添加Spring Web和Thymeleaf依赖项:

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

用户模型类

接下来,让我们创建一个User模型类,其中包含以下内容:

package net.javaguides.thymeleaf.model;

public class User {
    private String name;
    private String email;
    private String role;
    private String gender;

    public User(String name, String email, String role, String gender) {
        this.name = name;
        this.email = email;
        this.role = role;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

Spring MVC控制器-用户控制器

接下来,让我们使用处理程序方法创建一个Spring MVC控制器(UserController),以返回Thymeleaf模板,如下所示:

package net.javaguides.thymeleaf.controller;

import net.javaguides.thymeleaf.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    // handler method to handle variable-expression request
    @GetMapping("variable-expression")
    public String variableExpression(Model model){
        User user = new User("Ramesh", "ramesh@gmail.com", "ADMIN", "Male");
        model.addAttribute("user", user);
        return "variable-expression";
    }
}

只要springboot在类路径上找到springboot Thymeleaf starter依赖项,它就会自动为Thymleaf配置ViewResolver,因此我们不必手动为Thymelaaf配置e1d 3d1e。

Thymeleaf模板-variable-expression.html

以下是演示变量表达式用法的Thymeleaf模板:

<!DOCTYPE html>
<html lang="en"
    xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Variable Expressions</title>
</head>
<body>
<h1>Variable Expression Demo:</h1>
<h2>User Details:</h2>
<div>
    <p> Name: <strong th:text="${user.name}"></strong></p>
    <p> Email: <strong th:text="${user.email}"></strong></p>
    <p> Role: <strong th:text="${user.role}"></strong></p>
    <p> Gender: <strong th:text="${user.gender}"></strong></p>
</div>
</body>
</html>

演示:

运行Spring引导应用程


在浏览器中点击以下链接:
http://localhost:8080/variable-expression
输出如下:

相关文章