本文為開發者呈現了一些概念和相關的示例代碼,介紹了用ngResource($resource)服務POST方式提交數據到和服務器端SpringMVC環境下的RESTFul APIs。示例代碼可以在如下頁面找到:http://hello-angularjs.appspot.com/angularjs-restful-apis-post-method-code-example。相對於使用$http服務,我更喜歡這種方法的主要理由是ngResource允許你使用抽象方式(例如$resource類),你可以使用它的實例上的處理方法與RESTFul APIs交互。這樣就可以簡單方便地實現RESTFul集成。在$resource類的對象上,可以直接調用處理方法(例如get、save等)。因此,在其實例上,就可以使用"$"作為前綴直接調用這些方法。具體的例子如下所示。
這篇文章裡,用以下兩個情景用例來解釋:
保存/持久化 新的數據對象
更新存在的數據對象
代碼片段包含了AngularJs代碼和Spring MVC代碼,以能夠讓你簡單快速的上手。
想要$resource 服務工作,需要添加一段實際代碼:
應用angular-resource.js文件,你可以使用Google Hosted Libraries來實現。
下面采用的代碼是最新的angularJs版本。(下面就是引入服務的代碼)
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-resource.js">
</script>
下面的代碼告訴你如何在創建控制器時引入ngResource模塊和注入$resource服務:
var helloApp = angular.module("helloApp", [ 'ngResource' ]);
helloApp.controller("HttpController", [ '$scope', '$resource', function($scope, $resource) {
// // 在這寫你的實際業務代碼... // } ]);
保存/持久化新對象 (其實就是傳給後台存進數據庫的一個過程)
下面的代碼演示了如何使用POST方法提交form表單中的user信息(這部分是由controller來做),controller會把uers信息提交給REST URL “/user/new”(這部分是Spring MVC的控制器執行)。
AngularJS代碼
var helloApp = angular.module("helloApp", [ 'ngResource' ]);
helloApp.controller("HttpController", [ '$scope', '$resource', function($scope, $resource) {
$scope.users = [
{ 'firstname':'Ajitesh',
'lastname':'Shukla',
'address':'Hyderbad',
'email':'ajitesh101@gmail.com'},
{ 'firstname':'Sumit',
'lastname':'Jha',
'address':'Muzaffarpur',
'email':'sumitjha2011@yahoo.com'},
];
$scope.saveUser = function(){
// 創建一個resource對象 // var User = $resource('/user/new');
// 調用save方法 //(其實和我們$http.post(url,data).success(function(){})是一樣一樣的,只是它封裝一下而已) User.save({firstname:$scope.firstname,lastname:$scope.lastname,address:$scope.address,email:$scope.email}, function(response){
$scope.message = response.message;
});
}
} ]);
Spring MVC 代碼
請注意User對象的字段要和JSON數據的要一致。同時確保Jackson包已經引入了,並且正常工作了。這是最重要的步驟。我推薦參考這篇文章 how to fix 415 Unsupported Mediatype error 來幫助你實現前面兩個步驟。(1.Spring轉對象的時候,是按照字段名來轉的,比如你的Java的User對象的firstname會綁定Json對象的firstname,所以需要保持一致,否則幫出來的數據可能不對。2.不引人Jackson包,那麼Json對象和Java對象不能想換轉化,也就不能正常工作了)
/ 創建一個新user //
@RequestMapping(value = "/user/new", method = RequestMethod.POST) public @ResponseBody String saveUserRestful( @RequestBody User user ) {
// // 處理輸入參數的代碼 // String response = "{\"message\":\"Post With ngResource: The user firstname: " + user.getFirstname() + ", lastname: " + user.getLastname() + ", address: " + user.getAddress() + ", email: " + user.getEmail()+"\"}";
return response;
}
更新已存在的數據對象
下面的代碼演示了如何通過POST方法提交表單信息來更新user對象,請求會發送到服務器的REST URL "/user/{id}",也包括Spring MVC的方法。
AngularJS代碼
var helloApp = angular.module("helloApp", [ 'ngResource' ]);
helloApp.controller("HttpController", [ '$scope', '$resource', function($scope, $resource) {
$scope.users = [
{ 'firstname':'Ajitesh',
'lastname':'Shukla',
'address':'Hyderbad',
'email':'ajitesh101@gmail.com'},
{ 'firstname':'Sumit',
'lastname':'Jha',
'address':'Muzaffarpur',
'email':'sumitjha2011@yahoo.com'},
];
$scope.updateUser = function(){
// Create a resource class object // var User = $resource('/user/:userId', {userId:'@id'});
// Create an instance of User resource var user = User.get({userId:25});
// Update the new values entered in the form fields // user.id = 25;
user.firstname = $scope.firstname;
user.lastname = $scope.lastname;
user.address = $scope.address;
user.email = $scope.email;
// Call '$' prefixed action menthod to post ("save" ) // user.$save(function(response){
$scope.message = response.message;
});
// Push the new objects in the $scope.users // $scope.users.push({ 'firstname':$scope.firstname, 'lastname': $scope.lastname, 'address':$scope.address, 'email':$scope.email });
$scope.firstname='';
$scope.lastname='';
$scope.address='';
$scope.email='';
}
} ]);
Spring MVC 代碼
請注意下面幾點
-用例的路徑變量(就是"/user/{id}"這東西)
-Java的User對象要和Json對象匹配(字段名,或者說是屬性名)
-確保Jackson包引入並且正常工作(確保你後台能正常轉化Json和java對象)
// 更新 user
//
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST) public @ResponseBody String updateUserProfile( @PathVariable("id") long userId, @RequestBody User user ) {
// // Code processing the input parameters // String response = "{\"message\":\"Post With ngResource - id: " + String.valueOf( userId ) + ",firstname: " + user.getFirstname() + ", lastname: " + user.getLastname() + ", address: " + user.getAddress() + ", email: " + user.getEmail() +"\"}";
return response;
}
帶你走近AngularJS系列:
如何在 AngularJS 中對控制器進行單元測試 http://www.linuxidc.com/Linux/2013-12/94166.htm
在 AngularJS 應用中通過 JSON 文件來設置狀態 http://www.linuxidc.com/Linux/2014-07/104083.htm
AngularJS 之 Factory vs Service vs Provider http://www.linuxidc.com/Linux/2014-05/101475.htm
AngularJS 的詳細介紹:請點這裡
AngularJS 的下載地址:請點這裡