Java 如何将对象列表绑定到thymeleaf中的复选框?
我在用对象列表绑定复选框输入时遇到很多困难。问题是当我在输入字段类型复选框上添加th:field=“*{userRole}”时,我在web浏览器上收到错误的请求作为响应 这是我的密码: 用户模型类:Java 如何将对象列表绑定到thymeleaf中的复选框?,java,spring-mvc,thymeleaf,Java,Spring Mvc,Thymeleaf,我在用对象列表绑定复选框输入时遇到很多困难。问题是当我在输入字段类型复选框上添加th:field=“*{userRole}”时,我在web浏览器上收到错误的请求作为响应 这是我的密码: 用户模型类: public class User implements Serializable { private Integer id; private String username; private String password; private boolean enab
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);
}
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;
}
获取方法:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Map<String, Object> model) {
List<UserRole> roles = roleService.getAllRoles();
model.put("roles", roles);
return "index";
}
索引页格式:
<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}”我可以提交表单。有什么办法解决这个问题吗
---更新---
问题是无法直接绑定对象。所以添加了新的绑定字符串列表
private List<String> userRoles = new ArrayList<>(0);
private List 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>
试验
试验
谢谢 您正试图将
项
作为值添加到列表
。这就像试图说arraylistlist=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>
li th:each=“item,stat:${roles}”>
试验
我不确定这是否会直接解决您的问题,因为thymeleaf在简单地将对象“添加”到列表中时存在问题。Thymeleaf通常用于字符串和整数等基本类型。但至少我指出了你的问题所在。试着用这个到处乱跑。尝试使用这一行,至少这肯定会起作用:
<input type="checkbox" th:field="*{userRole[__${stat.index}__].role}" th:value="${item.role}" />
我尝试过,但仍然得到错误请求的响应,控制台上没有错误
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>
<input type="checkbox" th:field="*{userRole[__${stat.index}__].role}" th:value="${item.role}" />