Java字段报错:Failed to convert property value of type ‘java.lang.String‘ to required

825 阅读1分钟

遇到java接收前端日期字符串返回到后端Date字段时报错 Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date

解决方案一:

添加@DateTimeFormat(pattern="yyyy-MM-dd")注解

    private Integer uid;
    private String username;
    private String password;
    private String name;
    
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birthday;
    private String sex;

解决方案二:

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));
    }