SpringBoot 提交表单提示Validation failed for object

在SpringBoot中前台提交修改数据至后台提示错误

SpringBoot 提交表单提示Validation failed for object_第1张图片

问题解析

错误提示你,在校验对象数据的时候有错误数:3个。

我在Controller层的方法体里面打断点Debug,可根本就没走到就被拦截了,控制台也没任何的异常数据。

因为在校验数据的时候就过不去,所以压根就不会到断点处。

在表单提交时有时候会提示 Validation failed for object=’user’. Error count: 1,其中user是表的名字,Error count是对应数据库中出错的第几个字段,解决方法有两种:

  • 第一种 
    把表单中需要提交的数据按数据库中字段的顺序提交
  • 第二种 
    在表单对应的controller中添加BindingResult
  • 解决方法

    在Controller的参数中加入BindingResult result,例如

    @RequestMapping(value = "/update")
        @ResponseBody
        public Object update(Order order,BindingResult result) {
            if(result.hasErrors()){
                List ls = result.getAllErrors();
                for (int i = 0; i < ls.size(); i++) {
                    System.out.println("error:"+ls.get(i));
                }
            }
            orderService.updateById(order);
            return SUCCESS_TIP;
        }

    Java

    这样子就很从容的看到输出error的错误数据上面所说的3个value,然后再去分析错误。

    error:Field error in object 'order' on field 'expireTime': rejected value [2018-01-14]
    error:Field error in object 'order' on field 'lastTime': rejected value [2018-01-14];
    error:Field error in object 'order' on field 'regTime': rejected value [2018-01-14];

    我以上三个错误,是字段类型错误,我前台传的String,后台定义的Date;

    添加 BindingResult 的主要原因就是在 Validation 数据不通过的时候不会抛出异常!

    问题可以在修复后,去除BindingResult,也可以一直保留使用。

  • springboot默认的日期格式是用'/'分割的,如果提交'-'分割的格式到后台就会报这个错,此时需要在application.properties中修改默认格式

    spring.mvc.date-format=yyy-MM-dd

你可能感兴趣的:(SpringBoot 提交表单提示Validation failed for object)