spring mvc上编辑提交绑定实体的解决办法之一
spring mvc下编辑提交绑定实体的解决方法之一
我们经常需要更新一个实体,这时会有一下两个方法
- 这个方法用于取得现有的实体
@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET) public ModelAndView edit(HttpServletRequest request, @PathVariable Long id, @ModelAttribute Member member) { ModelAndView result = handleModelAndView(EDIT); Template template = templateServ.load(id); result.addObject("template", template); return result; }
- 这个方法用于接收修改后的实体
@RequestMapping(value = "/{id}/edit", method = RequestMethod.POST) public ModelAndView update(HttpServletRequest request, @PathVariable Long id, @ModelAttribute("template") @Valid Template template, BindingResult bindingResult) throws Exception { if(bindingResult.hasErrors()) {//出现错误 return handleErrors(bindingResult, NEW); } ModelAndView result = handleModelAndView(UPDATE); template = templateServ.load(id);
//这句是关键 bind(request, template); templateServ.update(template); return result; }
但是这个过程当中我发现如果这个实体有一个many-to-one或者one-to-many等实体关联的话,就会丢到这个信息,以至于无法完成更新。
解决方法:
在我的controller中使用的是注释方式,没有继承任何spring的control,但是现在需要继承
MultiActionController
这样,就有了一个bind(HttpServletRequest request, Object ob);的方法。这个方法可以帮助我们从request中绑定我们需要的的实体。