您的位置:首页 > 编程语言 > Java开发

SpringMvc日期类型转换问题

2017-01-14 17:52 351 查看
前台表单含有日期类型的字符串,提交后台时,需要注意做类型转换,以下提供极简的解决方案跟我处理时遇到的坑。

<input type="text" name="recordDate" value="2015-04-21" >


Http400错误:The request sent by the client was syntactically incorrect.

问题是由于没有告诉SpringMvc该如何处理该参数?前台表单都是字符串,而对应的实体属性是Date类型。

方案一:配置注解

@Entity
@Table(name = "exchange")
public class Exchange {
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date recordDate;// 记录日期
}


方案二:配置处理方法

//将该方法配置到Controller中,调用前,会做日期格式转换。
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));   //true为可以为空
}


一开始我使用以上两种方法都无法解决,一直400错误,后来我将Date的类型由java.sql.Date改为java.util.Date类型,解决了问题,估计是Spring转换时用的是后者。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息