2

I would like to build a form to save an User. I have 2 tables, User and UserRole as described in Spring Security. To save an user I need to create a User Object that contains a field Set. I want to create a list of checkboxes and map them into an Set of UserRoles, but I don't know how to map them with checkboxes. I have the following classes:

@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";
}
}

My 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>

User Role:

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;

}

}

And User:

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;
}*/

}

Thanks in advance.

1
  • I found ConverterFactory but I don't want to convert type (in this case List to Set<UserRoles>), I think there must be any mapping method in the controller Commented Jul 7, 2015 at 8:57

2 Answers 2

1

Refert this post, and i dont see the itemlabel and itemid attribute, which maps to userrole object.

also refer post

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but I saw both of them before. The first one is not useful because it only maps standard values, and the second one redirect in the end to a broken link, but maybe for someone are useful.
1

Found solution using Properties Editor. Here and here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.