我正在尝试将一个值和一个字符串[]发布到Spring MVC。我要么得到:
HTTP Status 400 - Required String[] parameter 'testCaseNames' is not present
如果我把它变成一个列表:
HTTP Status 400 - Required List parameter 'testCaseNames' is not present
那我应该输入什么类型?
var flowName = $('#flowName').val();
var testCaseNames = [];
$('.icons-right .action-icon:first-of-type').each(function() {
testCaseNames.push($(this).attr('name'))
});
console.log(testCaseNames);
$.ajax({
type: 'post',
url: '/create-flow/save',
data: {
flowName: flowName,
testCaseNames: testCaseNames
},
success: (function (result) {
})
});
@RequestMapping(value = "/create-flow/save" , method = RequestMethod.POST)
public @ResponseBody String saveFlow(HttpSession session, @RequestParam("flowName") String flowName, @RequestParam("testCaseNames") String[] testCaseNames)
{
String user = session.getAttribute("loggedUser").toString();
return TestFlow.addFlow(flowName,testCaseNames,user);
}
控制台输出:
["sdad", "xzxc"]
最佳答案
您将数据作为 REST 请求的 body
发布。
$.ajax({
type: 'post',
url: '/create-flow/save',
data: {
flowName: flowName,
testCaseNames: testCaseNames
},
success: (function (result) {
})
});
但是在您的 Controller 中,您收到的是RequestParams
。
@RequestParam("testCaseNames") String[] testCaseNames
这就是问题所在。
RequestParams 是您网址的一部分。例如,如果您的网址类似于
http://blahbla:1234?abcd=1234&defg=5677
那么abcd和defg就是请求参数。(这是发送数据的一种方式)
另一种方法是在消息正文中设置您在网址中看不到的数据,就像您现在所做的那样。
您有两种选择来解决此问题
1. 更改您的 ajax 请求以删除 data
部分,并在 url 中包含 testCaseNames 和 flowName,如下所示
$.ajax({
type: 'post',
url: '/create-flow/save?flowName='+flowName+'&testCaseNames='+testCaseNames,
success: (function (result) {
})
});
2.通过删除 requestParams 并创建一个以 testCaseNames 和 flowName 作为字段的类并接受它作为参数来更改您的 Controller 。
@RequestMapping(value = "/create-flow/save" , method = RequestMethod.POST)
public @ResponseBody String saveFlow(HttpSession session, @RequestBody SomeClass someclass)
{
.....
}
class SomeClass {
String flowName;
String testCaseNames; // Field Names should match exactly with what you send from frontend
// Gettter & Setters
}
关于javascript - 将简单数组传递给 Java Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148465/