您的位置:首页 > Web前端 > AngularJS

AngularJS —— 使用 ngResource、RESTful APIs 和 Spring MVC 框架提交数据

2014-11-23 15:01 260 查看


本文为开发者呈现了一些概念和相关的示例代码,介绍了用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;
}


原文地址:http://www.tuicool.com/articles/2UFVVbj
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: