在controller層中接收pojo數(shù)組時(shí)譬猫,一直報(bào)錯(cuò)聋亡,代碼如下:
java.lang.NoSuchMethodException: [Lcom.zq.spring.test.web.CartItem;.<init>()
at java.lang.Class.getConstructor0(Unknown Source) ~[na:1.8.0_191]
at java.lang.Class.getDeclaredConstructor(Unknown Source) ~[na:1.8.0_191]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:102) ~[spring-beans-4.3.21.RELEASE.jar:4.3.21.RELEASE]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:139) ~[spring-web-4.3.21.RELEASE.jar:4.3.21.RELEASE]
po類(只做簡(jiǎn)單定義):
public class CartItem {
private String cid;
private int count;
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
前端:
var cartItemArr = [];
cartItemArr.push({
cid : '1',
count : '2'
});
$.ajax({
url : '/makeOrder',
method: 'post',
data : {
cartItemArr : cartItemArr
}
});
controller:
@ResponseBody
@RequestMapping("/makeOrder")
public void testArr(CartItem[] cartItemArr) {
System.out.println(Arrays.toString(cartItemArr));
}
在加入@RequestParam后蝌焚,仍然錯(cuò)誤:
error: "Bad Request"
exception: "org.springframework.web.bind.MissingServletRequestParameterException"
message: "Required CartItem[] parameter 'cartItemArr[]' is not present"
path: "/makeOrder"
status: 400
timestamp: 1551692231933
個(gè)人猜測(cè)原因是因?yàn)樵趥鬏攺?fù)雜類型數(shù)組時(shí)泛源,mvc無(wú)法做到傳參篙挽,所以沒法init數(shù)組,以及強(qiáng)轉(zhuǎn)舍咖。
解決方法:
用@RequestBody傳輸json數(shù)據(jù)矩父,再轉(zhuǎn)為數(shù)組:
var cartItemArr = [];
cartItemArr.push({
cid : '1',
count : '2'
});
$.ajax({
url : '/makeOrder',
method: 'post',
contentType : 'application/json',
data : JSON.stringify(cartItemArr)
});
注意:若ajax中的data定義為:
$.ajax({
url : '/makeOrder',
method: 'post',
contentType : 'application/json',
data : {
cartItemArr : JSON.stringify(cartItemArr)
}
});
則會(huì)報(bào)錯(cuò):
error: "Bad Request"
exception: "org.springframework.http.converter.HttpMessageNotReadableException"
message: "JSON parse error: Unrecognized token 'cartItemArr': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'cartItemArr': was expecting ('true', 'false' or 'null')? at [Source: java.io.PushbackInputStream@9e8e171; line: 1, column: 13]"
path: "/makeOrder"
status: 400
timestamp: 1551692608346
原因是因?yàn)閖son數(shù)據(jù)格式錯(cuò)誤!
這個(gè)坑踩了大半天終于解決了排霉,開頭的異常信息也只是個(gè)人理解窍株,若有誤還請(qǐng)大神指導(dǎo)。