2015-10-05 81 views
0

我遇到了form:checkbox的问题。我无法让它显示选定的值。当我选择值并提交时,正确的值显示在数据库中。当我加载页面时,所有的值(复选框)都没有被选中。如何绑定Spring窗体:复选框而不是窗体:复选框?

单元下位于这里面:

<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"; 
} 

回答

0

调试会话后,我找到了解决办法。

因为Spring的内部构件JSP应该是这样的:

<c:forEach items="${availableRoles}" var="r"> 
    <div class="checkbox">       
     <form:checkbox path="roles" label="${r.description}" value="${r}" /> 
    </div> 
</c:forEach> 

注意值为项目(R),而不是项目的成员像r.id.

此外,您还需要在自定义PropertyEditor中执行getAsText。

@Override 
public String getAsText() { 
    Role role = (Role) this.getValue(); 
    return role.getId().toString(); 
} 
相关问题