springboot 提交时间字符串报错 Failed to convert property value of type 'java.lang.String' to required 'Date'

springboot 提交时间字符串匹配 Date 报错: Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

解决方法:

在实体类的属性上加上 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解。

如:  
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "LOGIN_TIME")
private Date loginTime;

另一种方法是在 controller 里加一个方法:

// 格式化页面传递到后台的 时间字符串 为 Date 类型
    @InitBinder
    protected void init( HttpServletRequest request, ServletRequestDataBinder binder ) {
        SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
        dateFormat.setLenient( false );
        binder.registerCustomEditor( Date.class, new CustomDateEditor( dateFormat, false ) );
    }

不过这种 @InitBinder 的方法,在页面提交一个空字符串到后台匹配 date 时会报错。

所以,还是应该使用 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 注解匹配后台的 Date 对象。

猜你喜欢

转载自blog.csdn.net/beguile/article/details/86687661