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