{% raw %}

AngularJS Spring MVC Rest 示例

原文: https://howtodoinjava.com/angularjs/angularjs-http-restful-api-example/

在这个 angularjs spring mvc crud 示例中,我们将学习使用 AngularJS $http服务来调用 RESTful API(HTTP GET,PUT,POST,DELETE)操作。 此外,我们将使用 RESTFul API 的响应来刷新此示例中使用的屏幕数据。

  1. Table of Contents
  2. 1\. Overview of example
  3. 2\. $http usage - for impatient
  4. 3\. RESTFul APIs used in example
  5. 4\. Client source code
  6. 5\. How example works?

1. 示例概述

在这个 angularjs spring mvc 示例应用中,我们将构建一个用于员工管理的屏幕。 您将可以使用各种链接和按钮从此屏幕中获取/添加/编辑/删除员工。 屏幕看起来像这样:

251.md - 图1

angular http 服务示例

屏幕选项非常简单。 您可以使用以下表格添加员工。 所有员工都列在上表中。 您可以通过单击该行中的“删除”链接来删除员工。 同样,单击编辑链接将在下面的表格中填充员工详细信息,您可以通过按提交按钮保存更改。

2. AngularJS $http用法 – 不耐烦

尽管我将在本教程的后面部分进行详细介绍,但是如果您急于阅读本节以了解对 REST API 的$http调用。

  • HTTP GET 操作


Angular $http可以以下方式用于调用 HTTP GET api。 在此示例中,此代码用于从服务器获取所有员工

  1. $http({
  2. method : 'GET',
  3. url : 'employees'
  4. }).then(function successCallback(response) {
  5. $scope.employees = response.data.employees;
  6. }, function errorCallback(response) {
  7. console.log(response.statusText);
  8. });


GET 调用上方使用相对 URL /employees。 如果当前位置为HTTP GET http://localhost:8080/myapplication,则会调用HTTP GET http://localhost:8080/myapplication/employees URL。 您也可以使用完整的应用网址,例如 “ http://localhost:8080/myapplication/employees”。 两种 URL 模式都可以使用。
默认情况下,angular 使用异步 HTTP 调用。 因此,我使用了两个函数successCallback()errorCallback(),它们将从服务器返回响应后由 angular 调用。

  • HTTP POST 操作


Angular $http可以以下方式用于调用 HTTP POST api。 在此示例中,此代码用于将员工添加到系统中。

  1. $http({
  2. method : "POST",
  3. url : "employees",
  4. data : angular.toJson($scope.form),
  5. headers : {
  6. 'Content-Type' : 'application/json'
  7. }
  8. }).then( _success, _error );


在上面的方法调用中,我已使用angular.toJson()方法以 JSON 格式传递了请求有效负载,然后将content-type标头参数设置为application/json

  • HTTP PUT 操作


Angular $http可以以下方式用于调用 HTTP PUT api。 在此示例中,此代码用于将员工更新到系统中。

  1. $http({
  2. method : "PUT",
  3. url : "employees/" + $scope.form.id,
  4. data : angular.toJson($scope.form),
  5. headers : {
  6. 'Content-Type' : 'application/json'
  7. }
  8. }).then( _success, _error );
  • HTTP DELETE 操作


Angular $http可以以下方式用于调用 HTTP DETELE api。 在此示例中,此代码用于将员工删除到系统中。

  1. $http({
  2. method : "DELETE",
  3. url : "employees/" + employee.id
  4. }).then( _success, _error );

3. 示例中使用的 Spring REST API

现在让我们看一下本示例中使用的 RESTful API。 这些是使用 Spring REST JSON 示例的源代码创建的。

  1. package com.howtodoinjava.demo.controller;
  2. import org.springframework.http.HttpStatus;
  3. import org.springframework.http.MediaType;
  4. import org.springframework.http.ResponseEntity;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import com.howtodoinjava.demo.model.EmployeeListVO;
  11. import com.howtodoinjava.demo.model.EmployeeVO;
  12. @Controller
  13. public class EmployeeRESTController
  14. {
  15. //Local storage of employees for demo; You will use database here
  16. private static EmployeeListVO employees = new EmployeeListVO();
  17. //add some employees here
  18. public EmployeeRESTController()
  19. {
  20. EmployeeVO empOne = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com");
  21. EmployeeVO empTwo = new EmployeeVO(2,"Amit","Singhal","asinghal@yahoo.com");
  22. EmployeeVO empThree = new EmployeeVO(3,"Kirti","Mishra","kmishra@gmail.com");
  23. employees.getEmployees().add(empOne);
  24. employees.getEmployees().add(empTwo);
  25. employees.getEmployees().add(empThree);
  26. }
  27. //Utility methods for getting employee by id
  28. private EmployeeVO _getEmployeeById(int id){
  29. for(EmployeeVO e : employees.getEmployees()){
  30. if(e.getId() == id){
  31. return e;
  32. }
  33. }
  34. return null;
  35. }
  36. /**
  37. * HTTP GET - Get all employees
  38. * */
  39. @RequestMapping(value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
  40. public ResponseEntity<EmployeeListVO> getAllEmployeesJSON()
  41. {
  42. return new ResponseEntity<EmployeeListVO>(employees, HttpStatus.OK);
  43. }
  44. /**
  45. * HTTP POST - Create new Employee
  46. * */
  47. @RequestMapping(value = "/employees", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
  48. public ResponseEntity<String> createEmployee(@RequestBody EmployeeVO employee)
  49. {
  50. employee.setId(employees.getEmployees().size() + 1);
  51. employees.getEmployees().add(employee);
  52. return new ResponseEntity<String>(HttpStatus.CREATED);
  53. }
  54. /**
  55. * HTTP PUT - Update employee
  56. * */
  57. @RequestMapping(value = "/employees/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.PUT)
  58. public ResponseEntity<EmployeeVO> updateEmployee(@PathVariable("id") int id, @RequestBody EmployeeVO employee)
  59. {
  60. EmployeeVO emp = _getEmployeeById(id);
  61. if(emp != null){
  62. emp.setFirstName(employee.getFirstName());
  63. emp.setLastName(employee.getLastName());
  64. emp.setEmail(employee.getEmail());
  65. return new ResponseEntity<EmployeeVO>(emp, HttpStatus.OK);
  66. }
  67. return new ResponseEntity<EmployeeVO>(HttpStatus.NOT_FOUND);
  68. }
  69. /**
  70. * HTTP DELETE - Delete employee
  71. * */
  72. @RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)
  73. public ResponseEntity<String> deleteEmployee(@PathVariable("id") int id)
  74. {
  75. EmployeeVO employee = _getEmployeeById(id);
  76. if(employee != null){
  77. employees.getEmployees().remove(employee);
  78. return new ResponseEntity<String>(HttpStatus.OK);
  79. }
  80. return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
  81. }
  82. }

4. 使用 angularjs 的 Spring MVC 视图代码

现在,让我们看看运行此示例的完整版本的客户端代码(HTML + AngularJS)。

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>
  6. AngularJS - REST Demo using $http service
  7. </title>
  8. <!-- Load AngularJS -->
  9. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  10. <script type="text/javascript">
  11. var app = angular.module("UserManagement", []);
  12. //Controller Part
  13. app.controller("UserManagementController", function($scope, $http) {
  14. //Initialize page with default data which is blank in this example
  15. $scope.employees = [];
  16. $scope.form = {
  17. id : -1,
  18. firstName : "",
  19. lastName : "",
  20. email : ""
  21. };
  22. //Now load the data from server
  23. _refreshPageData();
  24. //HTTP POST/PUT methods for add/edit employee
  25. $scope.submitEmployee = function() {
  26. var method = "";
  27. var url = "";
  28. if ($scope.form.id == -1) {
  29. //Id is absent so add employee - POST operation
  30. method = "POST";
  31. url = 'employees';
  32. } else {
  33. //If Id is present, it's edit operation - PUT operation
  34. method = "PUT";
  35. url = 'employees/' + $scope.form.id;
  36. }
  37. $http({
  38. method : method,
  39. url : url,
  40. data : angular.toJson($scope.form),
  41. headers : {
  42. 'Content-Type' : 'application/json'
  43. }
  44. }).then( _success, _error );
  45. };
  46. //HTTP DELETE- delete employee by Id
  47. $scope.removeEmployee = function(employee) {
  48. $http({
  49. method : 'DELETE',
  50. url : 'employees/' + employee.id
  51. }).then(_success, _error);
  52. };
  53. //In case of edit employee, populate form with employee data
  54. $scope.editEmployee = function(employee) {
  55. $scope.form.firstName = employee.firstName;
  56. $scope.form.lastName = employee.lastName;
  57. $scope.form.email = employee.email;
  58. $scope.form.id = employee.id;
  59. };
  60. /* Private Methods */
  61. //HTTP GET- get all employees collection
  62. function _refreshPageData() {
  63. $http({
  64. method : 'GET',
  65. url : 'employees'
  66. }).then(function successCallback(response) {
  67. $scope.employees = response.data.employees;
  68. }, function errorCallback(response) {
  69. console.log(response.statusText);
  70. });
  71. }
  72. function _success(response) {
  73. _refreshPageData();
  74. _clearForm()
  75. }
  76. function _error(response) {
  77. console.log(response.statusText);
  78. }
  79. //Clear the form
  80. function _clearForm() {
  81. $scope.form.firstName = "";
  82. $scope.form.lastName = "";
  83. $scope.form.email = "";
  84. $scope.form.id = -1;
  85. };
  86. });
  87. </script>
  88. <style>
  89. .button {
  90. cursor: pointer;
  91. color: blue;
  92. }
  93. td,th{
  94. border: 1px solid gray;
  95. width: 25%;
  96. text-align: left;
  97. }
  98. table {
  99. width: 600px;
  100. }
  101. </style>
  102. <head>
  103. <body ng-app="UserManagement" ng-controller="UserManagementController">
  104. <h1>
  105. AngularJS - Use $http to invoke RESTful APIs
  106. </h1>
  107. <table>
  108. <tr>
  109. <th>First Name</th>
  110. <th>Last Name</th>
  111. <th>Email</th>
  112. <th>Actions</th>
  113. </tr>
  114. <tr ng-repeat="employee in employees">
  115. <td>{{ employee.firstName }}</td>
  116. <td>{{ employee.lastName }}</td>
  117. <td>{{ employee.email }}</td>
  118. <td><a ng-click="editEmployee( employee )" class="button">Edit</a> | <a ng-click="removeEmployee( employee )" class="button">Remove</a></td>
  119. </tr>
  120. </table>
  121. <h2>Add/Edit Employee</h2>
  122. <form ng-submit="submitEmployee()">
  123. <table>
  124. <tr>
  125. <td>First Name</td>
  126. <td><input type="text" ng-model="form.firstName" size="60" /></td>
  127. </tr>
  128. <tr>
  129. <td>Last Name</td>
  130. <td><input type="text" ng-model="form.lastName" size="60" /></td>
  131. </tr>
  132. <tr>
  133. <td>Email</td>
  134. <td><input type="text" ng-model="form.email" size="60" /></td>
  135. </tr>
  136. <tr>
  137. <td colspan="2"><input type="submit" value="Submit" /></td>
  138. </tr>
  139. </table>
  140. </form>
  141. </body>
  142. </html>

5. Spring MVC angularjs 示例如何工作?

尽管我添加了源代码注解以使代码易于理解,但让我们逐步了解一些要点。

  1. 参见app.controller("UserManagementController", function($scope, $http)行。 它创建 Angular 控制器组件,并传递$http服务和$scope变量的相关性。 $http用于进行 REST 调用,$scope用于与页面数据进行交互。

  2. $scope具有两个数据元素。 $scope.employees引用页面中的所有员工集合,$scope.form映射到页面中的表单元素字段。

  3. 加载页面后,将调用_refreshPageData(),该调用将调用 HTTP GET api,以 JSON 格式从服务器获取所有员工数据。 检索到数据后,将使用$scope.employees = response.data.employees将其映射到$scope.employees。 该调用将自动刷新 UI,并使用员工数据填充表格。

  4. 使用ng-click="removeEmployee( employee )"将页面中的删除链接绑定到removeEmployee()函数。 该调用具有附加参数employee,该参数用于标识需要从表中删除哪个雇员(employee.id用于获取雇员 ID)。

  5. 类似地,编辑链接与ng-click="editEmployee( employee )"绑定。 在editEmployee()函数内部,我们通过下面的映射简单地使用现有员工数据填充表单文本字段。

    1. $scope.editEmployee = function(employee) {
    2. $scope.form.firstName = employee.firstName;
    3. $scope.form.lastName = employee.lastName;
    4. $scope.form.email = employee.email;
    5. $scope.form.id = employee.id;
    6. };


使用修改过的员工数据更新页面后,我们通过为表单字段分配空白值来清除表单。

  1. function _clearForm() {
  2. $scope.form.firstName = "";
  3. $scope.form.lastName = "";
  4. $scope.form.email = "";
  5. $scope.form.id = -1;
  6. };
  1. 对于 PUT 和 POST 方法,由于代码相似,我们使用了相同的函数来避免代码重复。 我们仅根据用户操作更改methodurl参数。

  2. 为了显示从服务器获取的用户集合,我们使用了ng-repeat="employee in employees"循环。

其余的事情几乎可以自我解释。 如果您有任何疑问或疑问,请在下面给我留言。

学习愉快!

{% endraw %}