Spring MVC - 将属性设置为控制器

时间:2016-07-15 04:40:39

标签: spring-mvc controller roles modelattribute spring-validator

我开始使用Spring,我发现了一个我无法解决的问题。 我有一个User实体,带有'roles'属性,'roles'是一个Set Object,其性能如下:

private String id;
private String name;
private String surname;
private String email;
private String identificationNumber;
private String username;
private String password;
private String passwordConfirm;
private int sex;
private Timestamp birthDate;
private Set<Role> roles;

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

我的'角色'实体如下:

private String id;
private String name;
private Set<User> users;

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@ManyToMany(mappedBy = "roles")
public Set<User> getUsers() {
    return users;
}

public void setUsers(Set<User> users) {
    this.users = users;
}

在jsp中我有一个带有所有'角色'列表的组合框

<spring:bind path="roles">
    <div class="input-field is-empty cell2">
        <form:select type="text" path="roles" class="validate ${status.error ? 'invalid' : ''}">
              <form:option value="NONE" selected="selected" disabled="true">Roles</form:option>
              <c:forEach items="${allRoles}" var="role">
                <form:option value="${role.getId()}" >${role.getName() }</form:option>
              </c:forEach>
          </form:select>
          <form:errors path="roles" class="alert alert-dismissible alert-danger">    </form:errors>
        <span class="material-input"></span>
    </div>
</spring:bind>

我选择一个或多个“角色”并将表单提交给后续控制器,在此存在一个@RequestParam,其中包含所选“角色”的ID列表

@RequestMapping(value="/user_edit/{id}", method=RequestMethod.POST)
public String edit_user(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, @PathVariable String id, @RequestParam String role_ids) {
    Set<Role> role_list = new HashSet<Role>();
    for (String role_id : role_ids.split(",")) {
        Role _role = roleService.getById(role_id);
        Role role = new Role();
        role.setName(_role.getName());
        role.setId(role_id);
        role_list.add(role);
    }
    userForm.setRoles(role_list);
    userValidator.validate(userForm, bindingResult, false);
    if (bindingResult.hasErrors()) {
        return "edit_user";
    }
    userService.save(userForm);
    return "redirect:/users";
}

在userValidator.validate行中(userForm,bindingResult,false);程序显示以下错误:

Failed to convert property value of type [java.lang.String[]] to required type [java.util.Set] for property roles; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.gestcart.account.model.Role] for property roles[0]: no matching editors or conversion strategy found

请帮助解决这个问题

1 个答案:

答案 0 :(得分:0)

您必须在User Entity中创建一个新字段作为String [] rolesSelect或List&lt;字符串&gt; rolesSelect。如果你想跳过它,它是瞬态的,因为它是一个实体类。然后你就可以从你的modelattribute“user”访问它了,你不需要一个单独的请求参数,即'&lt; spring:bind path =“roles”&gt;'不需要。 在jsp上使用以下代码:

<form:select type="text" path="rolesSelect" class="validate ${status.error ? 'invalid' : ''}">
          <form:option value="NONE" selected="selected" disabled="true">Roles</form:option>
          <c:forEach items="${allRoles}" var="role">
            <form:option value="${role.getId()}" >${role.getName() }</form:option>
          </c:forEach>
      </form:select>