简体   繁体   English

从thymeleaf复选框设置java.util.Set的值

[英]Set the values of java.util.Set from thymeleaf checkboxes

I'm creating Spring Boot application. 我正在创建Spring Boot应用程序。 I have class User where I am mapping (ManyToMany) with Role class. 我在类User中将Role类映射到(ManyToMany)。

I have role setter in User class as: 我在User类中的角色设置者为:

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

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

From Controller I use RoleRepository class to get names of all roles. 从Controller我使用RoleRepository类来获取所有角色的名称。 I am iterating it in html and creating checkbox: 我在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>

I want that when I click submit, the selected roles should be sent but it is returning null . 我希望当我单击提交时,应该发送选定的角色,但它返回null

You don't need to add: 您无需添加:

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

It is already managed by the Thymeleaf engine. 它已经由Thymeleaf引擎管理。

The problem may be related to allroles.roleList . 该问题可能与allroles.roleList有关。 You mentioned that you are getting only the names of the roles and your User requires a list of Role objects. 您提到您仅获得角色的名称,并且您的用户需要一个Role对象列表。 Please make sure that you are putting in the model a list of Role objects. 请确保您在模型中放置了一个Role对象列表。

If you want to use only the names of the roles, you should create another class UserForm with: 如果只想使用角色名称,则应使用以下命令创建另一个类UserForm:

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

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

You should add in the form the endpoint and Http method for clarity. 为了清楚起见,您应该以端点和Http方法的形式添加。 Example: 例:

<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>

Please make sure that in your controller you have @ModelAttribute 请确保您的控制器中具有@ModelAttribute

Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM