2. AngularJS $http 用法
- HTTP GET 操作
Angular$http可用于以以下方式调用 HTTP GET api。在此示例中,此代码用于从服务器获取所有员工。
$http({
method : 'GET',
url : 'employees'
}).then(function successCallback(response) {
$scope.employees = response.data.employees;
}, function errorCallback(response) {
console.log(response.statusText);
});
以上 GET 调用使用相对 URL /employees。如果当前位置是HTTP GET http://localhost:8080/myapplication,这将调用HTTP GET http://localhost:8080/myapplication/employeesURL。我们也可以使用完整的应用程序 URL,例如“http://localhost:8080/myapplication/employees”。两种 URL 模式都可以使用。
默认情况下,angular 使用异步 HTTP 调用。所以我使用了两个函数 successCallback()和 errorCallback(),它们将在服务器返回响应后由 angular 调用。
- HTTP POST 操作
Angular$http可用于以以下方式调用 HTTP POST api。在此示例中,此代码用于将员工添加到系统中。
$http({
method : "POST",
url : "employees",
data : angular.toJson($scope.form),
headers : {
'Content-Type' : 'application/json'
}
}).then( _success, _error );
在上面的方法调用中,我使用 angular.toJson()方法以 JSON 格式传递了请求负载,然后我将 content-type标头参数设置为 application/json。
- HTTP PUT 操作
Angular$http可用于以以下方式调用 HTTP PUT api。在此示例中,此代码用于将员工更新到系统中。
$http({
method : "PUT",
url : "employees/" + $scope.form.id,
data : angular.toJson($scope.form),
headers : {
'Content-Type' : 'application/json'
}
}).then( _success, _error );
- HTTP DELETE 操作
Angular$http可用于以以下方式调用 HTTP DETELE api。在本例中,此代码用于将员工删除到系统中。
$http({
method : "DELETE",
url : "employees/" + employee.id
}).then( _success, _error );
在这个 angularjs spring mvc crud 示例中,我们将学习使用 AngularJS $http服务来调用 RESTful API(HTTP GET、PUT、POST、DELETE)操作。
5. spring mvc angularjs 示例如何工作?
虽然我添加了源代码注释以使代码易于理解,但让我们来看看一些要点。
app.controller("UserManagementController", function($scope, $http)。它创建Angular控制器组件并传递$http服务和$scope变量的依赖。使用$http进行 REST 调用,$scope用于与页面数据交互。$scope有两个数据元素。$scope.employees引用页面中的所有员工集合,$scope.form映射到网页中的表单元素字段。- 当页面加载时,
_refreshPageData()被调用,它调用 HTTP GET api 以 JSON 格式从服务器获取所有员工数据。检索到数据后,使用$scope.employees = response.data.employees将其映射到$scope.employees。此调用会自动刷新 UI,并且表中会填充员工数据。 - 页面中的删除链接使用
ng-click="removeEmployee(employee)"绑定到removeEmployee()函数。此调用具有添加参数“employee”,用于标识需要从表中删除哪个员工(employee.id 用于获取员工 ID)。 - 同样,编辑链接与
ng-click="editEmployee(employee)"绑定。在editEmployee()函数中,我们通过以下映射简单地使用现有员工数据填充表单文本字段。
$scope.editEmployee = function(employee) {
$scope.form.firstName = employee.firstName;
$scope.form.lastName = employee.lastName;
$scope.form.email = employee.email;
$scope.form.id = employee.id;
};
使用修改后的员工数据更新页面后,我们通过为表单字段分配空白值来清除表单。
function _clearForm() {
$scope.form.firstName = "";
$scope.form.lastName = "";
$scope.form.email = "";
$scope.form.id = -1;
};
- 对于 PUT 和 POST 方法,由于代码相似,我们使用了相同的函数以避免代码重复。我们仅根据用户操作更改
method和url参数。 - 为了显示从服务器获取的用户集合,我们使用了
ng-repeat="employee in Employees"循环。
1. 示例概述
在这个 angularjs spring mvc 示例应用程序中,我们将为员工管理构建一个界面。
我们将能够使用各种链接和按钮从此页面中获取/添加/编辑/删除员工。
4. Spring MVC 视图代码与 angularjs
现在让我们看看使这个示例运行的客户端代码(HTML + AngularJS)的完整工作版本。
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>
AngularJS - REST Demo using $http service
</title>
<!-- Load AngularJS -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("UserManagement", []);
//Controller Part
app.controller("UserManagementController", function($scope, $http) {
//Initialize page with default data which is blank in this example
$scope.employees = [];
$scope.form = {
id : -1,
firstName : "",
lastName : "",
email : ""
};
//Now load the data from server
_refreshPageData();
//HTTP POST/PUT methods for add/edit employee
$scope.submitEmployee = function() {
var method = "";
var url = "";
if ($scope.form.id == -1) {
//Id is absent so add employee - POST operation
method = "POST";
url = 'employees';
} else {
//If Id is present, it's edit operation - PUT operation
method = "PUT";
url = 'employees/' + $scope.form.id;
}
$http({
method : method,
url : url,
data : angular.toJson($scope.form),
headers : {
'Content-Type' : 'application/json'
}
}).then( _success, _error );
};
//HTTP DELETE- delete employee by Id
$scope.removeEmployee = function(employee) {
$http({
method : 'DELETE',
url : 'employees/' + employee.id
}).then(_success, _error);
};
//In case of edit employee, populate form with employee data
$scope.editEmployee = function(employee) {
$scope.form.firstName = employee.firstName;
$scope.form.lastName = employee.lastName;
$scope.form.email = employee.email;
$scope.form.id = employee.id;
};
/* Private Methods */
//HTTP GET- get all employees collection
function _refreshPageData() {
$http({
method : 'GET',
url : 'employees'
}).then(function successCallback(response) {
$scope.employees = response.data.employees;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
function _success(response) {
_refreshPageData();
_clearForm()
}
function _error(response) {
console.log(response.statusText);
}
//Clear the form
function _clearForm() {
$scope.form.firstName = "";
$scope.form.lastName = "";
$scope.form.email = "";
$scope.form.id = -1;
};
});
</script>
<style>
.button {
cursor: pointer;
color: blue;
}
td,th{
border: 1px solid gray;
width: 25%;
text-align: left;
}
table {
width: 600px;
}
</style>
<head>
<body ng-app="UserManagement" ng-controller="UserManagementController">
<h1>
AngularJS - Use $http to invoke RESTful APIs
</h1>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
<tr ng-repeat="employee in employees">
<td>{{ employee.firstName }}</td>
<td>{{ employee.lastName }}</td>
<td>{{ employee.email }}</td>
<td><a ng-click="editEmployee( employee )" class="button">Edit</a> | <a ng-click="removeEmployee( employee )" class="button">Remove</a></td>
</tr>
</table>
<h2>Add/Edit Employee</h2>
<form ng-submit="submitEmployee()">
<table>
<tr>
<td>First Name</td>
<td><input type="text" ng-model="form.firstName" size="60" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" ng-model="form.lastName" size="60" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" ng-model="form.email" size="60" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
3. 示例中使用的 Spring REST API
现在让我们来看看本示例中使用的 RESTful API。
这些是使用 Spring REST JSON Example 的源代码创建的。
package com.onitroad.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.onitroad.demo.model.EmployeeListVO;
import com.onitroad.demo.model.EmployeeVO;
@Controller
public class EmployeeRESTController
{
//Local storage of employees for demo; You will use database here
private static EmployeeListVO employees = new EmployeeListVO();
//add some employees here
public EmployeeRESTController()
{
EmployeeVO empOne = new EmployeeVO(1,"Lokesh","Gupta","onitroad@gmail.com");
EmployeeVO empTwo = new EmployeeVO(2,"cherry","Singhal","asinghal@yahoo.com");
EmployeeVO empThree = new EmployeeVO(3,"Kirti","Mishra","kmishra@gmail.com");
employees.getEmployees().add(empOne);
employees.getEmployees().add(empTwo);
employees.getEmployees().add(empThree);
}
//Utility methods for getting employee by id
private EmployeeVO _getEmployeeById(int id){
for(EmployeeVO e : employees.getEmployees()){
if(e.getId() == id){
return e;
}
}
return null;
}
/**
* HTTP GET - Get all employees
* */
@RequestMapping(value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public ResponseEntity<EmployeeListVO> getAllEmployeesJSON()
{
return new ResponseEntity<EmployeeListVO>(employees, HttpStatus.OK);
}
/**
* HTTP POST - Create new Employee
* */
@RequestMapping(value = "/employees", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public ResponseEntity<String> createEmployee(@RequestBody EmployeeVO employee)
{
employee.setId(employees.getEmployees().size() + 1);
employees.getEmployees().add(employee);
return new ResponseEntity<String>(HttpStatus.CREATED);
}
/**
* HTTP PUT - Update employee
* */
@RequestMapping(value = "/employees/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.PUT)
public ResponseEntity<EmployeeVO> updateEmployee(@PathVariable("id") int id, @RequestBody EmployeeVO employee)
{
EmployeeVO emp = _getEmployeeById(id);
if(emp != null){
emp.setFirstName(employee.getFirstName());
emp.setLastName(employee.getLastName());
emp.setEmail(employee.getEmail());
return new ResponseEntity<EmployeeVO>(emp, HttpStatus.OK);
}
return new ResponseEntity<EmployeeVO>(HttpStatus.NOT_FOUND);
}
/**
* HTTP DELETE - Delete employee
* */
@RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteEmployee(@PathVariable("id") int id)
{
EmployeeVO employee = _getEmployeeById(id);
if(employee != null){
employees.getEmployees().remove(employee);
return new ResponseEntity<String>(HttpStatus.OK);
}
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
}
