Spring Form Ajax Request + Hibernate验证

时间:2012-02-12 17:19:03

标签: ajax hibernate spring spring-3 hibernate-validator

我总是使用@ValidBindingResult来验证表单字段。 现在使用基于this文章的Ajax,不可能使用BindingResult代替HttpServletResponse @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" ); } ,因为这会导致错误请求(HTTP错误代码400)。

如何验证我的表单字段?

  @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";
  }

这是没有ajax的旧方式:

errors

修改

试过这个,但是当结果未填充时,结果中没有true成员包含 @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; } (这应该会导致@NotEmpty约束消息)

{{1}}

1 个答案:

答案 0 :(得分:1)

似乎你正在使用hibernate验证器。如果是这样,试试这个

控制器中的

//other imports
import javax.validation.Validator;
@Controller()
class MyController{

    @autowire()
    @qualifier("myValidator")
    private Validator validator;
    public Validator getValidator() {
        return mValidator;
    }

    public void setValidator(Validator validator) {
        this.mValidator = validator;
    }

   @RequestMapping( value = "/save.html", params = "json", method = RequestMethod.POST )
   public @ResponseBody Map<String, ? extends Object> saveJSON( @RequestBody Location location, HttpServletResponse response )
   {
       Set<ConstraintViolation<Location>> errors = getValidator().validate(location);
       Map<String, String> validationMessages = new HashMap<String, String>();
       if(!errors.isEmpty())
       {
          //this map will contain the validation messages
          validationMessages = validationMessages(errors); 

          //probably you would like to send the errors back to client
          return validationMessages ;
       }
       else
       {
           //do whatever you like to do with the valid bean

       }
   }

   public Map<String, String> validationMessages(Set<ConstraintViolation<Location>> failures) {
        Map<String, String> failureMessages = new HashMap<String, String>();
        for (ConstraintViolation<Location> failure : failures) {

                failureMessages.put(failure.getPropertyPath().toString(), failure.getMessage());
        }
        return failureMessages;
    }



}

spring context 文件中添加以下bean

<beans:bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

希望它有所帮助:)