我正在向Spring控制器发送一个带有数组参数的Ajax GET请求,
$.ajax({
url: "getChoices",
dataType: "json",
type: "get",
data: {
'myarg': myarray // JS array of strings, ["a","b","c"]
// Verified to be correct
},
应接收此参数的控制器方法-- arg名称匹配:
@ResponseBody
@GetMapping("/getChoices")
public List<KeyValueBean> getChoices(List<String> myarg) {
//...
}
首先,在上面写的方式中,我得到了错误:
[java.lang.IllegalStateException: No primary or default constructor found for interface
java.util.List]
Caused by: java.lang.NoSuchMethodException: java.util.List.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:216)
然后我试着做了一些调整:
1)将方法签名设为String[]
,这不是我想要的--我需要一个列表--但为了以防万一,我尝试了一下:
public List<KeyValueBean> getChoices(String[] myarg) {
这进入了方法,但是myarg为空,并且没有正确设置。
2)保留了List<String>
,但尝试了阵列周围的JSON.stringify:
JSON.stringify(myarray)
相同的异常:[java.lang.IllegalStateException: No primary or default constructor found for interface java.util.List]
如何在Spring Boot中的Ajax GET请求中传递数组参数?
发布于 2019-05-09 10:15:53
您忘记使用@RequestParam
注释您的参数。
@GetMapping("/testList")
public void test(@RequestParam("myarg") List<String> myarg) {
for (String str : myarg) {
System.out.println(str);
}
}
您可以按如下方式向您的端点发出请求,它将正常工作。
http://localhost:8080/testList?myarg=abc,def
https://stackoverflow.com/questions/56047946
复制相似问题