比如說,現在需求是希望把前端的數據傳向SpringMVC,綁定在請求方法的一個實體參數中
@Request(value="test", method=RequestMethod.POST) @ResponseBody
public String test(TwoDate td) {
return td.toString();
}
其中,TwoDate是那個實體類,有兩個被@DateTimeFormat所標記的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');
}
});
并在請求方法的參數前面追加了個@RequestBody 注解,報了HTTP-400錯誤,控制臺提示我
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))
非常奇怪,而當我把實體類的兩個域的類型從Date改成String后,又正常了
3、我的dispatcherservlet.xml的配置關于消息轉換的配置是這樣的
<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>
所以我想問一下,實際開發中,向后端傳遞JSON字符串是否更合適?JSON字符串有辦法綁定到含有Date類型的實體中嗎?如果沒有辦法,那么大家的做法是否是將這些Date類型換成String類型嗎?
不勝感激:)
添加回答
舉報
0/150
提交
取消