i have a jsp to register new users with yours respective roles. In the form, i receive a roleList in checkbox using c:forEach.
Everything is going well, BUT...
- If i try to save User with the first checkbox checked = OK, it is saved well
- If i try to save User with the first and second checkbox checked = Ok again, everything going well
- BUT if i try to save the user with the second or third role, jumping one element in the checkbox sequence, it throws a Exception like: Exception Save the transient instance before flushing...
So, what i am understanding here, is that the list that is passed in the bind to my List cannot have blank/null values. Even if i have 20 roles, i can save Users, with many roles, but if i jump anyone, it throws the exception.
How can i resolve that issue?? How can i pass the roles that i want without follow any order?
@Entity
public class User implements UserDetails {
@Id
private String login;
@NotBlank
private String password;
@NotBlank
private String name;
@ManyToMany(fetch=FetchType.EAGER)
private List<Role> roles = new ArrayList<>();
@Entity
public class Role implements GrantedAuthority {
@Id
private String name;
@Controller
@Transactional
@RequestMapping("/register")
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class UserController {
@Autowired
UserDao userDao;
@Autowired
RoleDao roleDao;
@RequestMapping("userForm")
public ModelAndView userForm(User user) {
ModelAndView modelAndView = new ModelAndView("user/userForm");
modelAndView.addObject("roleList", roleDao.list());
return modelAndView;
}
@RequestMapping (value="saveUser", method=RequestMethod.POST, name="saveUser")
public ModelAndView saveUser(@Valid User user, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()){
return userForm(user);
}
userDao.save(user);
redirectAttributes.addFlashAttribute("success", "User successfully registered");
return new ModelAndView("redirect:/register/userForm");
}
}
<form:form action="${spring:mvcUrl('saveUser').build()}" method="post" commandName="user">
<div>
<label for="name">User name</label>
<form:input path="name"/>
<form:errors path="name"/>
</div>
<div>
<label for="login">Login</label>
<form:input path="login"/>
<form:errors path="login"/>
</div>
<div>
<label for="password">Password</label>
<form:input path="password"/>
<form:errors path="password"/>
</div>
<div>
<c:forEach items="${roleList}" var="role" varStatus="status">
<div>
<label for="role_${role}">${role}</label>
<input type="checkbox" value="${role}" name= "roles[${status.index}]" id="role_${role}"/>
</div>
</c:forEach>
</div>
<div>
<input type="submit" value="Save">
</div>
</form:form>
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire