我有一个JSP来注册新用户和你的各自角色。在表单中,我使用roleList
在复选框中收到c:forEach
。
一切进展顺利,但
所以,我在这里理解的是,绑定到我的List中传递的列表不能有空/空值。即使我有20个角色,我也可以保存具有许多角色的用户,但是如果我跳过任何人,它会抛出异常。
如何解决此问题?如何在没有特定订单的情况下传递我想要的角色?
@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>