springboot thymeleaf 标签实现 if else 的写法

95 篇文章 0 订阅

试了半天才试出来,thymeleaf 要用 switch 和 case 实现 if else:

<!-- 列表里显示 createTime -->
<td th:switch = "${ user.createTime != null }" >
    <div th:case="true" th:text = "${#dates.format( user.createTime , 'yyyy-MM-dd' )}" ></div>
    <div th:case="false" th:text = "‘---’" ></div>
</td>

很高兴回答您的问题!以下是Spring Boot与Thymeleaf实现个人信息展示的代码: 1. 添加Thymeleaf依赖 首先,我们需要通过Maven或Gradle将Thymeleaf依赖添加到我们的Spring Boot项目中。 Maven依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` Gradle依赖: ``` implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' ``` 2. 编写Controller类 接下来,我们需要编写一个Controller类来处理HTTP请求并返回视图。 ``` import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class PersonalInfoController { @GetMapping("/personal-info") public String showPersonalInfo(Model model) { // 构造用户信息 User user = new User("John Doe", "john.doe@example.com", 25); // 将用户信息添加到Model中 model.addAttribute("user", user); // 返回视图 return "personal-info"; } } ``` 在上面的代码中,我们使用了`@Controller`注解来标记这个类为一个Controller,使用`@GetMapping`注解来处理`/personal-info`路径的HTTP GET请求。 在`showPersonalInfo`方法中,我们构造了一个用户信息对象`user`,并将其添加到了`Model`对象中。`Model`对象是一个简单的容器,可以用来传递数据到视图中。 最后,我们返回一个名为`personal-info`的视图。这个视图文件将在下一步中进行创建。 3. 创建Thymeleaf视图 创建一个名为`personal-info.html`的Thymeleaf视图文件,并将其放置在`src/main/resources/templates`目录下。 在视图文件中,我们可以使用Thymeleaf标签和表达式来访问从Controller中传递过来的数据。 ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Personal Information</title> </head> <body> <h1>Personal Information</h1> <p>Name: <span th:text="${user.name}"></span></p> <p>Email: <span th:text="${user.email}"></span></p> <p>Age: <span th:text="${user.age}"></span></p> </body> </html> ``` 在上面的代码中,我们使用`<!DOCTYPE html>`声明了文档类型,并引入了Thymeleaf的命名空间。这样做可以让我们在视图中使用Thymeleaf标签和表达式。 在视图的`<body>`标签中,我们使用了`<h1>`标签来显示标题,使用了`<p>`标签来显示用户信息,使用了Thymeleaf的表达式`${user.name}`、`${user.email}`和`${user.age}`来访问Controller中传递过来的用户信息。 4. 启动应用程序,并访问链接 现在,我们可以启动Spring Boot应用程序,并在浏览器中访问`http://localhost:8080/personal-info`链接。如果一切正常,您应该会看到一个名为“Personal Information”的页面,其中包含用户信息的详细信息。 希望这能够解答您的问题!
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值