我正在尝试使用REST和Spring MVC构建我的应用程序。对于某些实体,我有特殊页面进行更新。数据提交后,验证。如果没有错误,它会重定向到该实体的视图,以便编辑页面。我必须在控制器之间传递数据(实体和验证器结果)吗?
这里实施了一些非常糟糕的做法。
@RequestMapping(method = RequestMethod.PUT, value = "/workers/{id}")
public ModelAndView update(@PathVariable final Long id, @Valid Worker entity, Errors errors, NativeWebRequest request) {
ModelAndView model = new ModelAndView();
entity.setId(id);
if (errors.hasErrors()) {
request.setAttribute("entity", entity, RequestAttributes.SCOPE_SESSION);
request.setAttribute("errors", errors.getAllErrors(), RequestAttributes.SCOPE_SESSION);
model.setViewName("redirect:/workers/" + entity.getId()+ "/edit");
} else {
System.out.println("upd-done");
service.update(entity);
model.setViewName("redirect:/workers/" + entity.getId());
model.addObject(entity);
}
return model;
}
@RequestMapping(method = RequestMethod.GET, value = "/workers/{id}/edit")
public ModelAndView updatePage(@PathVariable Long id, NativeWebRequest request) {
ModelAndView model = new ModelAndView();
DomainObject entity = (DomainObject)request.getAttribute("entity", RequestAttributes.SCOPE_SESSION);
model.addObject("entity", entity != null ? entity : service.get(id));
model.setViewName(names.provideViewName(Pages.EDIT));
return model;
}
此处可以进行编辑
<form id="entity" action="/workers/6" method="post"><input type="hidden" name="_method" value="PUT"/>
foo <input id="foo" name="foo" type="text" /></td>
<input type="submit" value="Save Changes" />
</form>
感谢。
答案 0 :(得分:1)
当出现错误并且您需要将用户发送回表单视图时,只需使用您在GET / edit方法中使用的相同视图名称(“names.provideViewName(Pages.EDIT)”)。您需要修改该视图以检查模型中是否存在错误,如果是,则将其显示给用户。
@RequestMapping(method = RequestMethod.PUT, value = "/workers/{id}")
public ModelAndView update(@PathVariable final Long id, @Valid Worker entity, Errors errors, NativeWebRequest request) {
ModelAndView model = new ModelAndView();
entity.setId(id);
if (errors.hasErrors()) {
model.addObject("entity", entity);
model.addObject("errors", errors);
model.setViewName(names.provideViewName(Pages.EDIT));
} else {
System.out.println("upd-done");
service.update(entity);
model.setViewName("redirect:/workers/" + entity.getId());
model.addObject(entity);
}
return model;
}