【发布时间】:2012-02-12 17:19:03
【问题描述】:
我一直使用@Valid 和BindingResult 来验证表单字段。
现在使用 Ajax,基于 this 文章,不能使用 BindingResult 代替 HttpServletResponse,因为这会导致错误请求(HTTP 错误代码 400)。
现在如何验证我的表单域?
@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 约束消息)
@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;
}
【问题讨论】:
-
你用的是哪个版本的spring 3.0还是3.1?
标签: ajax hibernate spring spring-3 hibernate-validator