比如說,現(xiàn)在需求是希望把前端的數(shù)據(jù)傳向SpringMVC,綁定在請(qǐng)求方法的一個(gè)實(shí)體參數(shù)中
@Request(value="test", method=RequestMethod.POST) @ResponseBody
public String test(TwoDate td) {
return td.toString();
}
其中,TwoDate是那個(gè)實(shí)體類,有兩個(gè)被@DateTimeFormat所標(biāo)記的Date類型的私有域。
1、我嘗試了一下以下的方式
$.ajax({
type:"post",
url:"/test",
data:saveData,
success:function(data) {
alert(data);
},
error:function(data) {
alert('error');
}
});
沒有問題,前端的saveData成功綁定到了TwoDate td中。
2、隨后,我換了以下的方式
$.ajax({
type:"post",
url:"/test",
dataType:"json",
contentType : 'application/json',
data:JSON.stringify(saveData),
success:function(data) {
alert(data);
},
error:function(data) {
alert('error');
}
});
并在請(qǐng)求方法的參數(shù)前面追加了個(gè)@RequestBody 注解,報(bào)了HTTP-400錯(cuò)誤,控制臺(tái)提示我
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotReadableFailed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.util.Date from String "2017-01-01 02:03:04": not a valid representation (error: Failed to parse Date value '2017-01-01 02:03:04': Can not parse date "2017-01-01 02:03:04Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))
非常奇怪,而當(dāng)我把實(shí)體類的兩個(gè)域的類型從Date改成String后,又正常了
3、我的dispatcherservlet.xml的配置關(guān)于消息轉(zhuǎn)換的配置是這樣的
<mvc:annotation-driven>
<mvc:message-converters>
<bean class = "org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
所以我想問一下,實(shí)際開發(fā)中,向后端傳遞JSON字符串是否更合適?JSON字符串有辦法綁定到含有Date類型的實(shí)體中嗎?如果沒有辦法,那么大家的做法是否是將這些Date類型換成String類型嗎?
不勝感激:)
JQ Ajax應(yīng)該選擇Json還是Json字符串向后端傳遞比較合適?
哆啦的時(shí)光機(jī)
2019-03-01 10:46:39