我创建了一个包含角色在内的一些信息的用户,我去了一个预先选择的用户角色下拉列表进行修改。现在我可以修改它但无法获取此用户的角色列表,在视图中,所有角色都存储在数据库中。
有人帮我解决了这个问题 这是我的百万美元代码来获取角色列表:
<select id="role" name="role" class="user-form-control"
multiple="multiple">
<option th:each="role : ${roles}" th:value="${role.name}"
th:attr="choiceid=${role.name}" th:text="${role.name}">
</option>
</select>
我的控制器:
@RequestMapping(value = "/users/edit/{userId}", method = RequestMethod.POST)
public RedirectView modifyUser(@PathVariable String userId, @ModelAttribute(value = "user") UserDto userto,
Model model) {
Integer valueUserId;
try {
valueUserId = Integer.parseInt(userId);
} catch (NumberFormatException e) {
return new RedirectView("/error");
}
UserDto user = userProvider.getUserById(valueUserId);
String pass = user.getPassword();
BeanUtils.copyProperties(userto, user);
user.setIdUser(valueUserId);
user.setPassword(pass);
return userProvider.modifyUser(user) ? new RedirectView("/users") : new RedirectView("/error");
}
我的角色控制器:
@RequestMapping(value = "/roles", method = RequestMethod.GET)
public ModelAndView getRoles(Model modelUser){
UserDto user = userService.getLoggedUser();
List<String> userRoles = user.getRole();
ModelAndView model = new ModelAndView("role/roles");
}
modelUser.addAttribute("userRoles", userRoles);
List<RoleDto> roles =roleProvider.getRoles();
model.addObject("roles",roles);
model.addObject("userRoles", userRoles);
return model;
}
@RequestMapping(value = "/roles/edit/{roleId}", method = RequestMethod.GET)
public ModelAndView getRole(@PathVariable String roleId){
Integer valueRoleId;
try{
valueRoleId = Integer.parseInt(roleId);
}
catch (Exception e){
return new ModelAndView("error");
}
RoleDto role = roleProvider.getRoleById(valueRoleId);
ModelAndView model;
if (role == null){
model = new ModelAndView("error");
}
else{
model = new ModelAndView("role/rolemodify");
model.addObject("role",role);
model.addObject("path","/roles/edit/"+role.getIdRole());
}
return model;
}
答案 0 :(得分:0)
你的角色控制器看起来很好。您可以像这样编辑您的modifyUser方法,以将您的角色添加到模板中:
@RequestMapping(value = "/users/edit/{userId}", method = RequestMethod.POST)
public RedirectView modifyUser(@PathVariable String userId, @ModelAttribute(value = "user") UserDto userto,
Model model) {
Integer valueUserId;
try {
valueUserId = Integer.parseInt(userId);
} catch (NumberFormatException e) {
return new RedirectView("/error");
}
//new code
List<RoleDto> roles = roleProvider.getRoles(); //maybe print these in a loop to verify it's getting the roles correctly from the database.
model.addAttributes("roles", roles);
UserDto user = userProvider.getUserById(valueUserId);
String pass = user.getPassword();
BeanUtils.copyProperties(userto, user);
user.setIdUser(valueUserId);
user.setPassword(pass);
return userProvider.modifyUser(user) ? new RedirectView("/users") : new RedirectView("/error");
}
您必须@Autowire
roleProvider
进入您的用户控制器。
确保您的RoleDto
类具有名称字段,并且getter为getName()
。命名约定在春天很重要。