POST request not getting mapped to Spring MVC Controller
我正在发送来自AngularJS$HTTP服务的POST请求。当我的承诺如下图所示并正确映射到弹簧控制器时,它工作得很好,
服务.js
1 2 3 4 5 6 7 8 9 10 11 | reassignKsaPendingLeads : function(data,username) { var promise = $http({ url :"reassignPendingLeads.htm", method :"POST", data : mydata }) .success(function(data, status, header, config, statusText) { } } |
弹簧控制器
1 2 3 4 5 6 | @RequestMapping({"reassignPendingLeads.htm" }) public @ResponseBody String updateAccessStatus(@RequestBody List<KsaLead> ksaLeads) { log.info("Inside updateAccessStatus"); return"true"; } |
号
我从service.js传递的json对象正被正确映射到@requestbody list ksaleads。因为JSON对象包含与ksalead的bean属性相同的键。
但现在我想传递除JSON主体(数据)之外的另一个参数用户名。然后我得到的请求方法"post"在Spring控制器中不受支持。
新服务.js
1 2 3 4 5 6 7 8 9 10 11 | reassignKsaPendingLeads : function(data,username) { var mydata = JSON.stringify(data) + '&username=' + username; var promise = $http({ url :"reassignPendingLeads.htm", method :"POST", data : mydata }) .success(function(data, status, header, config, statusText) { } |
新弹簧控制器
1 2 3 4 5 6 | @RequestMapping({"reassignPendingLeads.htm" }) public @ResponseBody String updateAccessStatus(@RequestBody List<KsaLead> ksaLeads,@RequestParam String username) { log.info("Inside updateAccessStatus"); return"true"; } |
。
有人能指导我如何从AngularJS传递数据,以便它正确映射到Spring控制器吗?
我假设您希望将用户名作为请求参数传递。为此,
1 2 3 4 5 6 7 8 9 | function(data,username) { var promise = $http({ url:"reassignPendingLeads.html", method:"POST", data: data, params: { username: username } }) // continue with your promise here } |
如果要在请求主体中传递它,我们必须执行以下步骤:
我们必须将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // we assume that data is not a primitive type function(data,username) { var mydata; // check if data is defined if (data) { // make a deep copy first, since we don't want to modify the input mydata = angular.copy(data); } else { // if the data is undefined, create e new object mydata = {}; } // add the username to mydata mydata.username = username; var promise = $http({ url:"reassignPendingLeads.html", method:"POST", data: mydata }) // continue with your promise here } |
号
在后端,我们必须确保能够接受这种数据。为此,建议创建一个数据类,其中包含用户名和可能出现在前端的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class MyDataClass { private String username; // other fields // no args constructor public MyDataClass() {} // all args constructor public MyDataClass(String username) { this.username = username; } // getter and setters } |
现在我们修改控制器以接受它:
1 2 3 4 5 6 | @RequestMapping(value ="reassignPendingLeads.htm", method = RequestMethod.POST) public @ResponseBody String updateAccessStatus(@RequestBody MyDataClass data) { log.info(data.getUsername()); return"true"; } |
。