2010-08-16 83 views
2

我正在做一個簡單的用戶crud。Spring-mvc 3.0 crud複選框問題

ApplicationUser具有以下屬性:

private Long id; 
private String password; 
private String username; 
private Collection<Authority> myAuthorities; 
private boolean isAccountNonExpired; 
private boolean isAccountNonLocked; 
private boolean isCredentialsNonExpired; 
private boolean isEnabled; 

管理局類有:

private Long id; 
private String authority; 
private String name; 

在我的JSP中,我認爲有以下形式:

<form:form modelAttribute="applicationUser" 
    action="add" method="post"> 
    <fieldset> 

    <form:hidden path="id" /> 

    <legend><fmt:message key="user.form.legend" /></legend> 
    <p><form:label for="username" path="username" cssErrorClass="error"><fmt:message key="user.form.username" /></form:label><br /> 
    <form:input path="username" /> <form:errors path="username" /></p> 

    <p><form:label for="password" path="password" 
     cssErrorClass="error"><fmt:message key="user.form.password" /></form:label><br /> 
    <form:password path="password" /> <form:errors path="password" /></p> 

    <p><form:label for="password" path="password" 
     cssErrorClass="error"><fmt:message key="user.form.password2" /></form:label><br /> 
    <form:password path="password" /> <form:errors path="password" /></p> 

    <p><form:label for="myAuthorities" path="myAuthorities" 
     cssErrorClass="error"><fmt:message key="user.form.autorities" /></form:label><br /> 
    <form:checkboxes items="${allAuthorities}" path="myAuthorities" itemLabel="name"/><form:errors path="myAuthorities" /></p> 

    <p><input type="submit"/></p> 
    </fieldset> 
</form:form> 

的JSP得到allAuthorities由此:

@ModelAttribute("allAuthorities") 
public List<Authority> populateAuthorities() { 
    return authorityService.findAll(); 
} 

當我填寫表格,我得到:

未能 java.lang.String類型的屬性值轉換爲所需的類型 java.util.Collection中的財產 myAuthorities;嵌套的異常是 java.lang.IllegalStateException: 無法轉換 類型的值[java.lang.String中]所需類型 [com.tda.model.applicationuser.Authority] 財產myAuthorities [0]:無 匹配編輯或轉換 找到策略

哪一種解決此問題的正確方法?

回答

4

當您的Authority是一個複雜的bean時,HTML表單僅使用字符串值。您需要配置PropertyEditor才能在AuthorityString之間執行轉換:

@InitBinder 
public void initBinder(WebDataBinder b) { 
    b.registerCustomEditor(Authority.class, new AuthorityEditor()); 
} 

private class AuthorityEditor extends PropertyEditorSupport { 
    @Override 
    public void setAsText(String text) throws IllegalArgumentException { 
     setValue(authorityService.findById(Long.valueOf(text))); 
    } 

    @Override 
    public String getAsText() { 
     return ((Authority) getValue()).getId(); 
    } 
}