【发布时间】:2015-10-05 20:00:13
【问题描述】:
我在使用 form:checkbox 时遇到问题。我不能让它显示选定的值。当我选择值并提交时,正确的值会显示在数据库中。当我加载页面时,所有值(复选框)都没有被选中。
下面的元素位于这个里面:
<form:form role="form" commandName="user" class="form-horizontal" action="${form_url}">
</form:form>
这很好用:
<form:checkboxes items="${availableRoles}" path="roles" itemLabel="role" itemValue="id" element="div class='checkbox'"/>
这不起作用:
<c:forEach items="${availableRoles}" var="r" varStatus="status">
<div class="checkbox">
<form:checkbox path="roles" label="${r.description}" value="${r.id}"/>
</div>
</c:forEach>
这是我的域类:
public class User {
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
这是我的自定义属性编辑器:
public class RolePropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
Role role = new Role();
role.setId(Integer.valueOf(text));
setValue(role);
}
}
控制器有这个方法:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Role.class, new RolePropertyEditor());
}
控制器方法:
@RequestMapping(value = "/update/{userId}", method = RequestMethod.GET)
public String updateUser(@PathVariable Integer userId, Model model) {
User user = userService.getByUserId(userId);
List<Role> availableRoles = roleService.getAllRoles();
model.addAttribute("availableRoles", availableRoles);
model.addAttribute("user", user);
return "user/update";
}
【问题讨论】:
标签: spring checkbox data-binding spring-form