Spring-mvc 3.0 crud with checkboxes问题

Mac*_*rse 3 spring jsp crud spring-mvc

我正在做一个简单的用户问题.

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;
Run Code Online (Sandbox Code Playgroud)

权威类有:

private Long id;
private String authority;
private String name;
Run Code Online (Sandbox Code Playgroud)

在我的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>
Run Code Online (Sandbox Code Playgroud)

jsp allAuthorities来自于:

@ModelAttribute("allAuthorities")
public List<Authority> populateAuthorities() {
  return authorityService.findAll();
}
Run Code Online (Sandbox Code Playgroud)

当我填写表格时,我得到:

无法将类型为java.lang.String的属性值转换为属性myAuthorities的必需类型java.util.Collection; 嵌套异常是java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为属性myAuthorities [0]所需的类型[com.tda.model.applicationuser.Authority]:找不到匹配的编辑器或转换策略

解决这个问题的正确方法是什么?

axt*_*avt 5

当您Authority是一个复杂的bean 时,HTML表单只能使用字符串值.您需要配置a 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();
    }
}
Run Code Online (Sandbox Code Playgroud)