Java后台接收字符串格式时间400失败问题

前端提交了一个表单后台做插入数据,表单里面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";

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值