前端提交了一个表单后台做插入数据,表单里面createTime是字符串的时间格式,对应后台的是Date类型的createTime字段,接收请求的时候报400参数错误,加上@RequestBody也没有用,网上查阅了一番,发现前端请求方法默认的contentType是application/x-www-form-urlencoded; 而@RequestBody注解需要使用contentType:"application/json"才可以把字符串时间转换为Java的Date类型。
前端传递的data也需要转成json格式。JSON.stringify(dataObject);
到此插入问题解决。
$.ajax({
type: "post",
contentType:"application/json",
url: "***/***",
data: JSON.stringify(dataObject),
success: function(data){
xxxxx(data);
}
})
还有一种办法
// 在控制层增加一个时间绑定器
@InitBinder
protected void dateBinder(WebDataBinder binder) {
// MessageQuery 是方法参数
SimpleDateFormat dateFormat = new SimpleDateFormat(DateJsonFormat.PATTERN);
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(MessageQuery.class, editor);
binder.registerCustomEditor(Date.class, editor);
}
// 时间格式
public class DateJsonFormat {
public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
public static final String YMD = "yyyy-MM-dd";
public static final String YM = "yyyy-MM";
public static final String TIMEZONE_BEIJING = "GMT+8";
}