【问题标题】:Spring Form Ajax Request + Hibernate ValidationSpring Form Ajax 请求 + Hibernate 验证
【发布时间】:2012-02-12 17:19:03
【问题描述】:

我一直使用@ValidBindingResult 来验证表单字段。 现在使用 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


【解决方案1】:

您似乎正在使用休眠验证器。如果是这样试试这个

在您的控制器中:

//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" />

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2013-05-08
    • 2023-01-21
    • 2018-06-20
    • 2018-01-24
    • 2016-09-20
    • 2016-01-16
    相关资源
    最近更新 更多