gpt4 book ai didi

java - 如何将对象列表绑定(bind)到 thymeleaf 中的复选框?

转载 作者:行者123 更新时间:2023-11-30 08:01:19 28 4
gpt4 key购买 nike

我在将复选框输入与对象列表绑定(bind)时遇到了很多困难。问题是当我在输入字段类型复选框上添加 th:field="*{userRole}" 然后我得到错误的请求作为网络浏览器的响应。

这是我的代码:

用户模型类:

public class User implements Serializable {
private Integer id;
private String username;
private String password;
private boolean enabled;
private List<UserRole> userRole = new ArrayList<UserRole>(0);
}

UserRole 模型类:

public class UserRole implements Serializable {
@Id
@GeneratedValue
private Integer userRoleId;
@ManyToMany(mappedBy = "userRole")
private List<User> users;
@Column(name = "role", nullable = false, length = 45)
private String role;
}

模型属性:

@ModelAttribute(value = "user")
public User userModel() {
return new User();
}

获取方法:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Map<String, Object> model) {
List<UserRole> roles = roleService.getAllRoles();
model.put("roles", roles);
return "index";
}

我的 POST 方法:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User userModel) {

}

索引页面形式:

<form role="form" action="#" th:action="@{/add}" th:object="${user}" method="post">

<div class="form-group">
<label for="email">User Name:</label>
<input type="text" class="form-control" id="username" th:field="*{username}" required autofocus>
</div>
<ul>
<li th:each="item : ${roles}">
<input type="checkbox" th:field="*{userRole}" th:value="${item}" />
<label th:text="${item.role}">Test</label>
</li>
</ul>
<input type="submit" value="Submit" />
</form>

当我点击提交时,浏览器显示为错误请求,但没有 th:field="*{userRole}" 我可以提交表单。有解决此问题的想法吗?

---更新---

问题是 Thymeleaf 无法直接绑定(bind)对象。所以添加了新的字符串列表用于绑定(bind)。

private List<String> userRoles = new ArrayList<>(0);

然后像@Roel 提到的那样改变了形式。

<li th:each="item, stat : ${roles}">
<label th:text="${stat.index}">Test</label>
<input type="checkbox" th:field="*{userRoles[__${stat.index}__]}" th:value="${item.userRoleId}" />
<label th:text="${item.role}">Test</label>
</li>

谢谢。

最佳答案

您正在尝试添加 item作为 List 的值.这就像试图说 ArrayList<Integer> list = 5;

您需要将项目添加到列表中:

    li th:each="item, stat : ${roles}">
<input type="checkbox" th:field="*{userRole[__${stat.index}__]}" th:value="${item}" />
<label th:text="${item.role}">Test</label>
</li>

我不确定这是否会直接解决您的问题,因为 thymeleaf 在简单地将对象“添加”到列表中时存在问题。 Thymeleaf 通常适用于基本类型,如字符串和整数。但至少我指出了你的问题所在。尝试稍微解决这个问题。尝试改用这一行,至少这肯定有效:

 <input type="checkbox" th:field="*{userRole[__${stat.index}__].role}" th:value="${item.role}" />

关于java - 如何将对象列表绑定(bind)到 thymeleaf 中的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37744826/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com