SpringBoot_遇到的问题

问题描述:用springboot写web项目时,在修改用户信息并提交时,发生如下错误:

Field error in object 'employee' on field 'birth': rejected value [2019-05-08]; codes [typeMismatch.employee.birth,typeMismatch.birth,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employee.birth,birth]; arguments []; default message [birth]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birth'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2019-05-08'; nested exception is java.lang.IllegalArgumentException]]

网页报错信息:

There was an unexpected error (type=Bad Request, status=400).

Validation failed for object='employee'. Error count: 1

大概意思应该是类型转换错误,传来的String类型无法匹配到Date数据类型上;

上网搜索了下解决方案:

  1.     @InitBinder
        public void init(WebDataBinder binder) {
            binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        }

    我是已经在application.properties中配置过了日期格式化(spring.mvc.data-format=yyyy-MM-dd),仍然有这样的问题,所以找到了这个解决方案,将这代码添加到Controller中,便可以解决。亲测。
    这个我记得好像是叫局部转换吧,还有一种是可以全局转换,具体忘记,自己搜搜应该是可以搜索到的,大致好像是创建一个处理类实现WebBindingInitializer,并在Spring-MVC.xml中配置日期转换,嗯。
    这里补充一点,使用这个方案,若页面传来的就是空字符串,那么也会报错。

  2. public String addEmp(Employee employee, BindingResult  bindingResult){
       // todo
    }

    就是添加一个参数:BindingResult bindingResult,是可以解决,但是传过来的数据是null,也就是说他并没有真的解决问题,只是捕获并处理的异常。不推荐

  3. 正在我要提交草稿的时候,发现还有一种方案,使用过后也是有效的。就是在实体类的属性上添加@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解。

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
    private Date birth;

    就是如果页面传来的数据格式和后台这里定义的不一致,仍然会报错。

Thanks♪(・ω・)ノ

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值