在controller层中接收pojo数组时,一直报错,代码如下:
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类(只做简单定义):
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后,仍然错误:
error: "Bad Request"
exception: "org.springframework.web.bind.MissingServletRequestParameterException"
message: "Required CartItem[] parameter 'cartItemArr[]' is not present"
path: "/makeOrder"
status: 400
timestamp: 1551692231933
个人猜测原因是因为在传输复杂类型数组时,mvc无法做到传参,所以没法init数组,以及强转。
解决方法:
用@RequestBody传输json数据,再转为数组:
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)
}
});
则会报错:
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
原因是因为json数据格式错误!
这个坑踩了大半天终于解决了,开头的异常信息也只是个人理解,若有误还请大神指导。