SpringBoot_遇到的问题

  • Post author:
  • Post category:其他


问题描述:用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♪(・ω・)ノ



版权声明:本文为Eeeeearl原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。