您的(@)Controller类中的方法效率不高。您不想(手动)检索对象并将所有字段,关系等复制到该对象上。除了复杂的对象,您早晚或会遇到麻烦。
您想要的是第一种方法(用于显示表单的GET)来检索用户并将其存储在会话中
@SessionAttributes。接下来,您需要一个带
@InitBinder注释的方法将验证器设置为,
WebDataBinder以便spring进行验证。这将使您的
updateFromForm方法更干净。
@Controller@RequestMapping("/edit/{id}")@SessionAttributes("student")public EditStudentController @Autowired private StudentFormValidator validator; @Autowired private StudentRepository studentRep; @InitBinder public void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping(method=RequestMethod.GET) public String showUpdateForm(Model model) { model.addObject("student", studentRep.secureFind(id)); return "students/form"; } @RequestMapping(method=RequestMethod.POST) public String public String updateFromForm(@Valid @ModelAttribute Student student, BindingResult result, RedirectAttributes redirectAttributes, SessionStatus status) { // Optionally you could check the ids if they are the same. if (result.hasErrors()) { return "students/form"; } redirectAttributes.addFlashAttribute("message", "?p?t???? p??s????!"); studentRep.save(student); status.setComplete(); // Will remove the student from the session return "redirect:/students/list"; }}您将需要将
SessionStatus属性添加到方法中并标记处理完成,以便Spring可以从会话中清理模型。
这样,您就不必在对象等周围复制。Spring会进行所有的升举,并且所有字段/关系都将正确设置。



