Spring-MVC 3.0 Crud with Checkboxes问题
问题内容:
我正在做一个简单的用户任务。
我的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的属性值转换为属性myAuthorities所需的类型java.util.Collection;嵌套异常为java.lang.IllegalStateException:无法将属性myAuthorities
[0]的类型[java.lang.String]的值转换为所需的类型[com.tda.model.applicationuser.Authority]:找不到匹配的编辑器或转换策略
哪个是解决此问题的正确方法?
问题答案:
当您Authority
是复杂的bean
时,HTML表单仅适用于字符串值。您需要配置,PropertyEditor
以在Authority
和之间执行转换String
:
@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();
}
}