I am doing an simple user crud.
My ApplicationUser
has the following properties:
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;
Authority class has:
private Long id;
private String authority;
private String name;
In my jsp, my view has the following form:
<form:form modelAttribute="applicationUser"
action="add" method="post">
<fieldset>
&开发者_StackOverflowlt;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>
The jsp gets allAuthorities
from this:
@ModelAttribute("allAuthorities")
public List<Authority> populateAuthorities() {
return authorityService.findAll();
}
When I fill the form I get:
Failed to convert property value of type java.lang.String to required type java.util.Collection for property myAuthorities; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.tda.model.applicationuser.Authority] for property myAuthorities[0]: no matching editors or conversion strategy found
Which is the correct way to solve this?
HTML forms work with string values only, when your Authority
is a complex bean. You need to configure a PropertyEditor
to perform conversion between Authority
and 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();
}
}
精彩评论