从百里叶复选框设置 java.util.Set 的值



我正在创建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.

您不需要添加:

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

它已经由Thymeleaf引擎管理。

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

如果只想使用角色的名称,则应使用以下内容创建另一个类用户窗体:

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

最新更新