我正在做一个简单的用户问题。
我的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]:没有 匹配编辑或转换 战略发现
解决这个问题的正确方法是什么?
答案 0 :(得分:5)
当您的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();
}
}