1. 简介
本文将介绍如何在 Thymeleaf 中使用 Java 枚举类型(enum)。
我们会从一个下拉菜单展示枚举值开始,接着讲解如何在模板中使用枚举进行流程控制。
2. 环境准备
首先,我们需要在 Spring Boot 项目中添加 Thymeleaf 的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>3.1.5</version>
</dependency>
接下来,我们定义一个表示颜色的枚举类 Color
:
public enum Color {
BLACK, BLUE, RED, YELLOW, GREEN, ORANGE, PURPLE, WHITE
}
再定义一个 Widget
类,用于绑定表单数据:
public class Widget {
private String name;
private Color color;
// 标准 getter/setter 方法
}
3. 在下拉菜单中显示枚举值
我们使用 Thymeleaf 的 select
和 option
标签来渲染枚举值:
<select name="color">
<option th:each="colorOpt : ${T(com.baeldung.thymeleaf.model.Color).values()}"
th:value="${colorOpt}" th:text="${colorOpt}"></option>
</select>
📌 说明:T()
是 Spring Expression Language (SpEL) 的语法,用于访问类的静态方法或字段。
运行应用后,你会看到下拉菜单中列出了所有枚举值:
提交表单后,选中的颜色会正确绑定到 Widget
对象中:
4. 使用更友好的显示名称
如果直接显示枚举名(如 BLACK
),对用户来说不够友好。我们可以为每个枚举值添加显示名称。
修改 Color
枚举如下:
public enum Color {
BLACK("Black"),
BLUE("Blue"),
RED("Red"),
YELLOW("Yellow"),
GREEN("Green"),
ORANGE("Orange"),
PURPLE("Purple"),
WHITE("White");
private final String displayValue;
private Color(String displayValue) {
this.displayValue = displayValue;
}
public String getDisplayValue() {
return displayValue;
}
}
然后在 Thymeleaf 模板中使用这个 displayValue
属性:
<select name="color">
<option th:each="colorOpt : ${T(com.baeldung.thymeleaf.model.Color).values()}"
th:value="${colorOpt}" th:text="${colorOpt.displayValue}"></option>
</select>
现在下拉菜单的显示就更人性化了:
5. 使用 if 语句控制显示内容
有时候我们需要根据枚举值动态控制页面内容。可以使用 Thymeleaf 的 th:if
实现。
比如,当颜色为红色时显示警告信息:
<div th:if="${widget.color == T(com.baeldung.thymeleaf.model.Color).RED}">
This color screams danger.
</div>
也可以通过字符串比较判断:
<div th:if="${widget.color.name() == 'GREEN'}">
Green is for go.
</div>
6. 使用 switch-case 语句
除了 if
,Thymeleaf 还支持 switch-case
语句,适用于多个条件判断。
我们来根据颜色显示不同的提示信息:
<div th:switch="${widget.color}">
<span th:case="${T(com.baeldung.thymeleaf.model.Color).RED}"
style="color: red;">Alert</span>
<span th:case="${T(com.baeldung.thymeleaf.model.Color).ORANGE}"
style="color: orange;">Warning</span>
<span th:case="${T(com.baeldung.thymeleaf.model.Color).YELLOW}"
style="color: yellow;">Caution</span>
<span th:case="${T(com.baeldung.thymeleaf.model.Color).GREEN}"
style="color: green;">All Good</span>
</div>
当选中橙色时,会显示相应的提示信息:
7. 小结
本文我们学习了如何在 Thymeleaf 中使用枚举类型:
✅ 在下拉菜单中展示枚举值
✅ 添加更友好的显示名称
✅ 使用 if
和 switch-case
根据枚举值控制页面内容显示
完整示例可在 GitHub 上查看。