2
我总是使用@Valid
和BindingResult
来验证表单域。 现在使用基于this文章的Ajax,不可能使用BindingResult
而不是HttpServletResponse
,因为这会导致请求错误(HTTP错误代码400)。春季表单Ajax请求+休眠验证
如何验证我的表单字段?
@RequestMapping(value = "/save.html", params = "json", method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> saveJSON(@RequestBody Location location, /* BindingResult result, */ HttpServletResponse response)
{
return Collections.singletonMap("foo", "foobar");
}
这是没有Ajax的老路上:
@RequestMapping(value = "/save.html", method = RequestMethod.POST)
public String save(@ModelAttribute("location") @Valid Location location, BindingResult result, Map<String, Object> map)
{
Location l;
if ((l = service.findByTitle(location.getTitle())) != null)
{
if (location.getId() != l.getId())
{
result.addError(new FieldError("location", "title", messageSource.getMessage("Unique.location.title", null, null)));
}
}
if (result.hasErrors())
{
return "locationform";
}
service.save(location);
return "redirect:/locations/index.html";
}
编辑
想这一点,但没有errors
成员离开形式填充在其中包含true
结果(这一点应引起@NotEmpty Constraint message)
@RequestMapping(value = "/save.html", params = "json", method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> saveJSON(@RequestBody Location location, HttpServletResponse response, Map<String, Object> map)
{
BindingResult result = new BeanPropertyBindingResult(location, "");
if (result.hasErrors()) map.put("errors", true);
map.put("foo", "foobar");
return map;
}
哪个版本的春天你用3.0还是3.1? – Ralph 2012-02-12 19:17:36
@Ralph我使用弹簧3.1 – dtrunk 2012-02-12 19:30:01