Thymeleaf th:switch的用法(附带实例)
Thymeleaf 中使用 th:switch、th:case 标签进行多条件判断,与 Java 中的 switch 语句等效,根据条件显示匹配的内容,如果有多个匹配结果,只选择第一个显示。
th:case="*" 表示默认选项,即没有 case 的值为 true 时显示 th:case="*" 的内容,对应 Java 中 switch 的 default。
下面以数据状态为例来演示 th:switch 的用法:
1) 创建前端页面。在 templates 目录下创建 switch.html 页面,示例代码如下:
2) 添加后端程序:
3) 运行验证。启动项目,在浏览器中输入地址 http://localhost:8080/switch,页面显示效果如下图所示。

图 1 switch.html 页面显示效果
页面显示“进行中”的状态,可以在后台更改 status 的值来查看结果。由上图可知,switch.html 页面通过后台返回的 status 的值来显示不同的内容。
th:case="*" 表示默认选项,即没有 case 的值为 true 时显示 th:case="*" 的内容,对应 Java 中 switch 的 default。
下面以数据状态为例来演示 th:switch 的用法:
1) 创建前端页面。在 templates 目录下创建 switch.html 页面,示例代码如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"></meta> <title>Example switch </title> </head> <body> <h1>Thymeleaf模板引擎</h1> <h3>switch</h3> <div > <div th:switch="${status}"> <p th:case="'todo'">未开始</p> <p th:case="'doing'">进行中</p> <p th:case="'done'">完成</p> <!-- *: case的默认选项 --> <p th:case="*">状态错误</p> </div> </div> </body> </html>在上面的示例代码中,使用 th:switch、th:case 标签根据后台返回的 status 的值显示匹配数据。
2) 添加后端程序:
@RequestMapping("/switch") public String switchcase(ModelMap map) { map.addAttribute("status", "doing"); return "switch"; }在上面的示例中,后台返回 switch.html 页面,同时返回 status 值为 doing。
3) 运行验证。启动项目,在浏览器中输入地址 http://localhost:8080/switch,页面显示效果如下图所示。

图 1 switch.html 页面显示效果
页面显示“进行中”的状态,可以在后台更改 status 的值来查看结果。由上图可知,switch.html 页面通过后台返回的 status 的值来显示不同的内容。