处理接收前台日期字串到后端Date字段时报错Failed to convert property value of type 'java.lang.String' to required type '

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateExpire'; 
nested exception is org.springframework.core.convert.ConversionFailedException: 
Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2029-03-12'; nested exception is java.lang.IllegalArgumentException]

在Controller里添加InitBinder即可:

@InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

若当字符串为空内容(“”)时将日期对象处理成null,把如下参数改成true即可(allow Empty):

new CustomDateEditor(dateFormat, true);

 

你可能感兴趣的:(Java后端)