前台表单含有日期类型的字符串,提交后台时,需要注意做类型转换,以下提供极简的解决方案跟我处理时遇到的坑。
<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转换时用的是后者。