如何使用 th:each 和 th:value 动态生成一组复选框?如何判断某选项是否被选中?

解读

国内一线面试官问这道题,表面看是“写一段循环”,实质想确认三件事:

  1. 你是否真的把 Thymeleaf 当成“自然模板”来用——页面能在设计师的 Dreamweaver 里直接双击打开,不报错。
  2. 你是否理解“选中状态”必须由服务端一次性算好,而不是让前端再跑一段 JS 去“二次回显”。
  3. 你是否熟悉 Spring MVC 的表单对象命名规约,能把 List/Set 优雅地绑定到提交后的 Controller,避免 400 或 415。

因此,回答时要给出“可运行、可预览、可提交”的完整闭环,而不是只贴两行 th:each。

知识点

  1. th:each 的迭代变量与状态变量:iterStat 可以取 index、count、size、current、even、odd、first、last。
  2. th:value 的写值优先级:它会先找 model 中的同名属性,找不到才当字面量,因此必须用 ${} 显式求值。
  3. th:field 与 th:checked 的取舍:
    • th:field="*{roles}" 只能用于单值属性,对复选框数组会生成 name='roles' 但无法决定 checked;
    • 正确姿势是用 th:checked="${user.roles.contains(role.id)}",让 Thymeleaf 在渲染期直接打 checked 属性。
  4. 自然模板兼容性:input 标签里同时出现 value 和 th:value,浏览器只看 value;Thymeleaf 解析后会把 th:value 结果覆盖进去,设计器不会报错。
  5. 提交后的绑定:Spring Boot 要求表单 name 写成 roles[],但 Thymeleaf 的 th:field 会自动追加 [],手工写 th:name 时别重复。

答案

【需求场景】 用户修改页面,要把“全部角色列表”渲染成复选框,并回显该用户已有的角色;提交后 Controller 用 List<Long> 接收。

【DTO 准备】

public class UserForm {
    private Long id;
    private List<Long> roles = new ArrayList<>(); // 已选角色ID
    // getter/setter 省略
}

【Controller 两段式】

@GetMapping("/user/edit")
public String edit(@RequestParam Long id, Model model) {
    List<Role> allRoles = roleService.list();          // 全部角色
    UserForm form = userService.getForm(id);           // 包含已选roles
    model.addAttribute("allRoles", allRoles);
    model.addAttribute("form", form);
    return "user/edit";
}

@PostMapping("/user/update")
public String update(@Valid UserForm form) {
    userService.updateRoles(form.getId(), form.getRoles());
    return "redirect:/user/list";
}

【自然模板片段】

<div class="form-group">
    <label>角色分配</label>
    <div class="checkbox-wrapper" th:each="role : ${allRoles}">
        <input type="checkbox"
               th:id="|role_${role.id}|"
               th:value="${role.id}"
               th:checked="${form.roles != null and form.roles.contains(role.id)}"
               th:name="roles"
               th:class="custom-checkbox"/>
        <label th:for="|role_${role.id}|" th:text="${role.name}">角色名</label>
    </div>
</div>

【关键点说明】

  1. th:name="roles" 让 Spring 绑定到 UserForm.roles;Thymeleaf 会自动补 [],生成 name="roles[]"。
  2. th:checked 使用 contains 判断,渲染期即产生 checked 属性,无需 JS。
  3. 设计师双击静态原型时,input 的 value 和 checked 都是字面量,不会报错,实现“所见即所得”。

拓展思考

  1. 性能优化:如果角色表很大,可以把 form.roles 转成 Set<Long> selectedRoleIds,避免每次循环都触发 list.contains()。
  2. 安全加固:在提交端再用 Spring Security 的 @PreAuthorize 校验一次角色范围,防止用户伪造请求提交越权角色。
  3. 国际化:角色名称存在 i18n 文件时,用 #{role.${role.code}} 配合 MessageSource 实现多语言,无需改 HTML。
  4. 前端无刷新追加:若产品要求“动态添加新角色并立即勾选”,可结合 Thymeleaf 的 片段 + SSE 或 HTMX,把新增角色行以服务器推送方式插入,同样保持自然模板特性。