【问题标题】:Set the values of java.util.Set from thymeleaf checkboxes从 thymeleaf 复选框设置 java.util.Set 的值
【发布时间】:2017-09-17 06:41:08
【问题描述】:

我正在创建 Spring Boot 应用程序。我有 User 类,我正在与 Role 类映射(ManyToMany)。

我在User 类中有角色设置器:

public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

从控制器我使用RoleRepository 类来获取所有角色的名称。 我在 html 中迭代它并创建复选框:

<form th:object="${userForm}">
  <!-- userForm is coming from controller: -->
  <!-- model.addAttribute("userForm", new User()); -->
  <div class="checkbox" th:each="role: ${allroles.roleList}">
    <input th:field="*{roles}" type="checkbox" th:value="${role}">
    <input th:field="*{roles}" type="hidden" th:value="${role}">
    <td th:text="${role}"></td>
  </div>
</form>

我希望当我点击提交时,应该发送所选角色,但它返回null

【问题讨论】:

    标签: java spring jpa thymeleaf


    【解决方案1】:

    你不需要添加:

    <input th:field="*{roles}" type="hidden" th:value="${role}"/>
    

    它已经由 Thymeleaf 引擎管理。

    问题可能与 allroles.roleList 有关。您提到您只获得角色的名称,并且您的用户需要角色对象列表。 请确保您将角色对象列表放入模型中。

    如果您只想使用角色的名称,您应该创建另一个类 UserForm :

    public Set<String> getRoles() {
       return roles;
    }
    
    public void setRoles(Set<String> roles) {
       this.roles = roles;
    }
    

    为了清楚起见,您应该在表单中添加端点和 Http 方法。 示例:

    <form th:object="${userForm}" th:action="@{/user}" method="post">
       <div class="checkbox" th:each="role: ${allRoles}">
        <label th:text="${role.name}"></label>
        <input th:field="*{roles}" type="checkbox" th:value="${role}"/>
       </div>
       <input type="submit"/>
    </form>
    

    请确保您的控制器中有@ModelAttribute

    例子:

    @PostMapping("/user")
    public String submitUser(@ModelAttribute("userForm") User user) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      相关资源
      最近更新 更多