我尝试使用spring和thymeleaf创建简单的形式。这是我的代码:
@GetMapping("users/{id}")
public String editUser(@PathVariable long id, Model model)
{
User user = userService.findByID(id);
Iterable<Role> roles= roleService.findAll();
UserEditForm userEditForm = new UserEditForm(user);
model.addAttribute("userEditForm", userEditForm);
model.addAttribute("allRoles", roles);
return "admin/userEdit";
}
@PostMapping("users/{id}")
public String updateUser(@PathVariable long id, @ModelAttribute UserEditForm userEditForm,
BindingResult bindingResult)
{
userEditValidator.validate(userEditForm, bindingResult);
if (bindingResult.hasErrors()) {
return "admin/userEdit";
}
User user = new User(userEditForm);
userService.save(user);
return "redirect:/admin/users/{id}";
}
几乎所有事情都按照预期行事。当形式上有错误时,我唯一不理解的是缺少allRoles
modelAttribute(列表为空)(我会重定向回来纠正它们)。我认为可能会重置模型对象,但userEditForm与Get请求中的相同。我错过了什么吗?如果不是我怎么能纠正它?不确定再次从db获取角色是个好主意。
编辑:
根据评论的建议,我想出了类似的东西(效果很好):
@GetMapping("users/{id}")
public String editUser(@PathVariable long id, Model model, HttpSession session)
{
User user = userService.findByID(id);
Iterable<Role> roles= roleService.findAll();
UserEditForm userEditForm = new UserEditForm(user);
model.addAttribute("userEditForm", userEditForm);
model.addAttribute("allRoles", roles);
session.setAttribute("allRoles", roles);
return "admin/userEdit";
}
@PostMapping("users/{id}")
public String updateUser(@PathVariable long id, @ModelAttribute UserEditForm userEditForm,
BindingResult bindingResult, @SessionAttribute("allRoles") Iterable<Role> roles,
Model model, SessionStatus sessionStatus)
{
userEditValidator.validate(userEditForm, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("allRoles", roles);
return "admin/userEdit";
}
User user = new User(userEditForm);
userService.save(user);
sessionStatus.setComplete();
return "redirect:/admin/users";
}
现在刚收到一些问题。
这是最好的方法吗?或者我应该在需要时查询数据库&#34;角色&#34;?或者也许是一些不同的方法
2. UserEditForm
对象如何得到&#34;自动注入&#34;到模型(我可以在视图中使用它),而我需要在model.addAttribute()
方法中使用roles
调用updateUser
?
答案 0 :(得分:0)
根据评论的建议,我想出了类似的东西(效果很好):
@GetMapping("users/{id}")
public String editUser(@PathVariable long id, Model model, HttpSession session)
{
User user = userService.findByID(id);
Iterable<Role> roles= roleService.findAll();
UserEditForm userEditForm = new UserEditForm(user);
model.addAttribute("userEditForm", userEditForm);
model.addAttribute("allRoles", roles);
session.setAttribute("allRoles", roles);
return "admin/userEdit";
}
@PostMapping("users/{id}")
public String updateUser(@PathVariable long id, @ModelAttribute UserEditForm userEditForm,
BindingResult bindingResult, @SessionAttribute("allRoles") Iterable<Role> roles,
Model model, SessionStatus sessionStatus)
{
userEditValidator.validate(userEditForm, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("allRoles", roles);
return "admin/userEdit";
}
User user = new User(userEditForm);
userService.save(user);
sessionStatus.setComplete();
return "redirect:/admin/users";
}