这是控制器的代码
@RequestMapping(value = "/fetchRecord/", method = RequestMethod.POST)
@ResponseBody
public String fetchRecord(Integer primaryKey)
{
return this.serviceClass.fetchRecord(primaryKey);
}
这是我的角度代码
var dataObj = {
primaryKey : $scope.primaryKey
};
var res = $http.post('/Practice/learn/fetchRecord/', dataObj);
res.success(function(data, status, headers, config) {
$scope.firstname = data;
});
res.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({
data : data
}));
});
我能够调试我的代码。尽管我可以在浏览器中检查它,以使主键的值通过。但仍然在控制器中为null。
有什么可能的原因?
您应该发送一个JSON对象,
尝试这个,
var dataObj = {
primaryKey : $scope.primaryKey
};
var res = $http.post('/Practice/learn/fetchRecord/', angular.toJson(dataObj));
您可以从两种方式中获得Controller
中的值:
第一个选项:
分配一个具有要通过的属性的对象。假设您具有RecordEntity
对象,它具有一些属性,其中之一是Integer primaryKey
。注释@RequestBody
将接收值,因此控制器将为:
后端
@RequestMapping(value = "/fetchRecord/", method = RequestMethod.POST)
@ResponseBody
public String fetchRecord(@RequestBody RecordEntity recordEntity) {
return "primaryKey from requestBody: " + recordEntity.getPrimaryKey();
}
frontend
在前端您应该发送一个具有primaryKey
属性的json
,例如:
http://localhost:8080/Practice/learn/fetchRecord/
帖子主体:
{
"primaryKey": 123
}
您的控制器将在RecordEntity
对象中接收值。
第二选项:
通过URL传递该值,注释@RequestParam
将接收该值,因此控制器将为:
后端
@RequestMapping(value = "/fetchRecord", method = RequestMethod.POST)
@ResponseBody
public String fetchRecord(@RequestParam Integer primaryKey) {
return "primaryKey from RequestParam: " + primaryKey;
}
frontend
在URL中,您应该使用?primaryKey
发送值,例如
http://localhost:8080/Practice/learn/fetchRecord?primaryKey=123
您的控制器将在Integer primaryKey
中接收值。