弹簧绑定复选框与对象集

时间:2015-07-07 08:13:46

标签: java forms jsp spring-mvc checkbox

我想构建一个表单来保存用户。我有两个表,用户和UserRole,如Spring Security中所述。要保存用户,我需要创建一个包含字段集的用户对象。我想创建一个复选框列表并将它们映射到一组UserRoles,但我不知道如何使用复选框映射它们。我有以下课程:

@Controller
public class UserController {

@Autowired
IUserService userService;

/** Default GET form handler for users, in submission will call saveRegistration */
@RequestMapping(value="/createuser",  method=RequestMethod.GET)
public String createUser(Model model) {
    // User form will be bind to this User object
    model.addAttribute("user", new User()); 

    // Code about adding the user roles to JSP?
    // Maybe something like this?:
    // User u = new User ("useruser","123456",false);
    // Set<UserRole> roles = new HashSet<UserRole>();  
    // roles.add(new UserRole(u,"ROLE_ADMIN"));  
    // roles.add(new UserRole(u,"ROLE_USER"));   
    // model.addAttribute("roles", roles); 

    return "createuser";
}

/** This method will be called on form submission, handling POST request,
 * It also validates the user input */
@RequestMapping(value="/createuser", method=RequestMethod.POST)
public String doCreateUser(Model model, @Valid User user,  BindingResult result) {
    if(result.hasErrors()) {
        return "createuser";
    }
    userService.createUser(user,user.getUserRole()) //createUser(User user, Set<UserRole> role)
    return "success";
}
}

我的JSP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="resources/css/createuser.css" />
</head>
<body onload='document.createUserForm.username.focus();'>


<sf:form name="createUserForm" method="post"
    action="${pageContext.request.contextPath}/createuser"
    commandName="user">

    <table class="formtable">
        <tr>
            <td class="label">Username:</td>
            <td><sf:input class="control" path="username" name="username"
                    type="text" /><br />
                <div class="error">
                    <sf:errors path="username"></sf:errors>
                </div></td>
        </tr>
        <tr>

            <td class="label">Role:</td>

            <td>
            <ul>  
            <sf:checkboxes element="li" path="userRole" items="${roles}"></sf:checkboxes>
            </ul></td>
        </tr>
        <tr>
            <td class="label">Password:</td>
            <td><sf:input class="control" path="password" name="password"
                    type="password" />
                <div class="error">
                    <sf:errors path="password"></sf:errors>
                </div></td>
        </tr>
        <tr>
            <td class="label">Confirm Password:</td>
            <td><input class="control" name="confirmpass" type="password" />
                <div class="error">
                    <sf:errors path="password"></sf:errors>
                </div></td>
        </tr>
        <tr>
            <td class="label"></td>
            <td><input class="control" value="Create account" type="submit" /></td>
        </tr>
    </table>

</sf:form>

用户角色:

public class UserRole {

private Integer userRoleId;
private User user;
private String role;

public UserRole () {

}

public UserRole(User user, String role) {
    this.user = user;
    this.role = role;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "user_role_id", 
    unique = true, nullable = false)
public Integer getUserRoleId() {
    return userRoleId;
}

public void setUserRoleId(Integer userRoleId) {
    this.userRoleId = userRoleId;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false)
public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

@Column(name = "role", nullable = false, length = 45)
public String getRole() {
    return role;
}

public void setRole(String role) {
    this.role = role;
}

public String toString () {
    return role;

}

}

用户:

public class User {


@NotNull
@NotBlank(message="Username cannot be blank.")
@Size(min=4, max=15, message="Username must be between 4 and 15 characters long.")
@Pattern(regexp="^\\w{6,}$", message="Username can only consist of numbers, letters and the underscore character.")
private String username;

@NotBlank(message="Password cannot be blank.")
@Pattern(regexp="^\\S+$", message="Password cannot contain spaces.")
@Size(min=6, message="Username must be longer than 6 characters.")
private String password;

//private String confirmPassword;


private boolean enabled;

private Set<UserRole> userRole = new HashSet<UserRole>(0);

public User() {
}

public User(String username, String password, boolean enabled) {
    this.username = username;
    this.password = password;
    this.enabled = enabled;
}

public User(String username, String password, 
    boolean enabled, Set<UserRole> userRole) {
    this.username = username;
    this.password = password;
    this.enabled = enabled;
    this.userRole = userRole;
}

@Id
@Column(name = "username", unique = true, nullable = false, length = 45)
public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

@Column(name = "password", nullable = false, length = 60)
public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

@Column(name = "enabled", nullable = false)
public boolean isEnabled() {
    return enabled;
}

public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
public Set<UserRole> getUserRole() {
    return userRole;
}

public void setUserRole(Set<UserRole> userRole) {
    this.userRole = userRole;
}

/*public String getConfirmPassword() {
    return confirmPassword;
}

public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
}*/

}

提前致谢。

2 个答案:

答案 0 :(得分:1)

重新发布this帖子,我没有看到itemlabel和itemid属性,它们映射到userrole对象。

也请参考post

答案 1 :(得分:1)

使用“属性编辑器”找到解决方案Herehere