AngularJS Spring Data REST CRUD 應用

REST,Spring Data
Remote
1
12:56 PM · Dec 01 ,2025

1. 概述

在本教程中,我們將使用 AngularJS 作為前端和 Spring Data REST 作為後端創建一個簡單的 CRUD 應用程序示例。

2. 創建 REST 數據服務

為了支持持久化,我們將使用 Spring Data REST 規範,以便我們可以對數據模型執行 CRUD 操作。

您可以在 Spring Data REST 的介紹中找到所有必要的關於如何設置 REST 端點的詳細信息。 在本文中,我們將重用我們為介紹教程設置的現有項目。

對於持久化,我們將使用 H2 在內存數據庫中使用。

作為數據模型,前一篇文章定義了一個 WebsiteUser 類,具有 idnameemail 屬性以及 UserRepository 接口。

定義此接口會指示 Spring 創建支持公開 REST 集合資源和項目資源的支持。 讓我們更詳細地瞭解我們稍後從 AngularJS 調用提供的端點。

2.1. 集合資源

所有用户的列表將可用在端點 /users。 此 URL 可以使用 GET 方法調用,並將返回格式為 JSON 對象的:

{
  "_embedded" : {
    "users" : [ {
      "name" : "Bryan",
      "age" : 20,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/1"
        },
        "User" : {
          "href" : "http://localhost:8080/users/1"
        }
      }
    }, 
...
    ]
  }
}

2.2. 項目資源

單個 WebsiteUser 對象可以通過訪問格式為 /users/{userID} 的 URL 並使用不同的 HTTP 方法和請求負載進行操作。

要檢索 WebsiteUser 對象,我們可以訪問 /users/{userID} 並使用 GET 方法。 這將返回格式為 JSON 對象的:

{
  "name" : "Bryan",
  "email" : "[email protected]",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/1"
    },
    "User" : {
      "href" : "http://localhost:8080/users/1"
    }
  }
}

要添加新的 WebsiteUser,我們需要調用 /users 並使用 POST 方法。 新 WebsiteUser 記錄的屬性將作為 JSON 對象添加到請求主體中:

{name: "Bryan", email: "[email protected]"}

如果未發生錯誤,此 URL 將返回 201 CREATED 狀態碼。

如果我們想更新 WebsiteUser 記錄的屬性,則需要調用 URL /users/{UserID} 並使用 PATCH 方法,請求主體包含新值:

{name: "Bryan", email: "[email protected]"}

要刪除 WebsiteUser 記錄,我們可以調用 URL /users/{UserID} 並使用 DELETE 方法。 如果未發生錯誤,這將返回 204 NO CONTENT 狀態碼。

2.3. MVC 配置

我們還將添加基本的 MVC 配置以在我們的應用程序中顯示 HTML 文件:

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
    
    public MvcConfig(){
        super();
    }
    
    @Override
    public void configureDefaultServletHandling(
      DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

   @Bean
   WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() {
     return (factory) -> factory.setRegisterDefaultServlet(true);
   }
}

2.4. 允許跨域請求

如果我們想將 AngularJS 前端應用程序部署到 REST API 的單獨位置,則需要啓用跨域請求。

Spring Data REST 已添加對從版本 1.5.0.RELEASE 開始支持此功能。 要允許來自不同域的請求,只需將 @CrossOrigin 註解添加到存儲庫中:

@CrossOrigin
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends CrudRepository<WebsiteUser, Long> {}

作為結果,在從 REST 端點響應的每個響應中,將添加 Access-Control-Allow-Origin 標頭。

3. Creating the AngularJS Client

For creating the front end of our CRUD application, we’ll use – a well-known JavaScript framework that eases the creation of front-end applications.

In order to use , we first need to include the angular.min.js file in our users.html page:

<script 
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js">
</script>

Next, we need to create an Angular module, controller, and service that will call the REST endpoints and display the returned data.

These will be placed in a JavaScript file called app.js that also needs to be included in the users.html page:

<script src="view/app.js"></script>

3.1. Angular Service

First, let’s create an Angular service called UserCRUDService that will make use of the injected $http service to make calls to the server. Each call will be placed in a separate method.

Let’s take a look at defining the method for retrieving a user by id using the $/users/{userID} endpoint:

app.service('UserCRUDService', [ '$http', function($http) {

    this.getUser = function getUser(userId) {
        return $http({
            method : 'GET',
            url : 'users/' + userId
        });
    }
} ]);

Next, let’s define the addUser method which makes a POST request to the $/users URL and sends the user values in the data attribute:

this.addUser = function addUser(name, email) {
    return $http({
        method : 'POST',
        url : 'users',
        data : {
            name : name,
            email: email
        }
    });
}

The updateUser method is similar to the one above, except it will have an id parameter and makes a PATCH request:

this.updateUser = function updateUser(id, name, email) {
    return $http({
        method : 'PATCH',
        url : 'users/' + id,
        data : {
            name : name,
            email: email
        }
    });
}

The method for deleting a WebsiteUser record will make a DELETE request:

this.deleteUser = function deleteUser(id) {
    return $http({
        method : 'DELETE',
        url : 'users/' + id
    })
}

And finally, let’s take a look at the methods for retrieving the entire list of users:

this.getAllUsers = function getAllUsers() {
    return $http({
        method : 'GET',
        url : 'users'
    });
}

All of these service methods will be called by an controller.

3.2. Angular Controller

We will create an UserCRUDCtrl controller that will have an UserCRUDService injected and will use the service methods to obtain the response from the server, handle the success and error cases, and set $scope variables containing the response data for displaying it in the HTML page.

Let’s take a look at the getUser() function that calls the getUser(userId) service function and defines two callback methods in case of success and error. If the server request succeeds, then the response is saved in a user variable; otherwise, error messages are handled:

app.controller('UserCRUDCtrl', ['$scope','UserCRUDService', 
  function ($scope,UserCRUDService) {
      $scope.getUser = function () {
          var id = $scope.user.id;
          UserCRUDService.getUser($scope.user.id)
            .then(function success(response) {
                $scope.user = response.data;
                $scope.user.id = id;
                $scope.message='';
                $scope.errorMessage = '';
            },
    	    function error (response) {
                $scope.message = '';
                if (response.status === 404){
                    $scope.errorMessage = 'User not found!';
                }
                else {
                    $scope.errorMessage = "Error getting user!";
                }
            });
      };
}]);

The addUser() function will call the corresponding service function and handle the response:

$scope.addUser = function () {
    if ($scope.user != null &amp; $scope.user.name) {
        UserCRUDService.addUser($scope.user.name, $scope.user.email)
          .then (function success(response){
              $scope.message = 'User added!';
              $scope.errorMessage = '';
          },
          function error(response){
              $scope.errorMessage = 'Error adding user!';
              $scope.message = '';
        });
    }
    else {
        $scope.errorMessage = 'Please enter a name!';
        $scope.message = '';
    }
}

The updateUser() and deleteUser() functions are similar to the one above:

$scope.updateUser = function () {
    UserCRUDService.updateUser($scope.user.id, 
      $scope.user.name, $scope.user.email)
      .then(function success(response) {
          $scope.message = 'User data updated!';
          $scope.errorMessage = '';
      },
      function error(response) {
          $scope.errorMessage = 'Error updating user!';
          $scope.message = '';
      });
}

$scope.deleteUser = function () {
    UserCRUDService.deleteUser($scope.user.id)
      .then (function success(response) {
          $scope.message = 'User deleted!';
          $scope.User = null;
          $scope.errorMessage='';
      },
      function error(response) {
          $scope.errorMessage = 'Error deleting user!';
          $scope.message='';
      });
}

And finally, let’s define the function that retrieves a list of users, and stores it in the users variable:

$scope.getAllUsers = function () {
    UserCRUDService.getAllUsers()
      .then(function success(response) {
          $scope.users = response.data._embedded.users;
          $scope.message='';
          $scope.errorMessage = '';
      },
      function error (response) {
          $scope.message='';
          $scope.errorMessage = 'Error getting users!';
      });
}

3.3. HTML Page

The users.html page will make use of the controller functions defined in the previous section and the stored variables.

First, in order to use the ng-app property:

<html ng-app="app">

Then, to avoid typing UserCRUDCtrl.getUser() every time we use a function of the controller, we can wrap our HTML elements in a div with a ng-controller property set:

<div ng-controller="UserCRUDCtrl">

Let’s create the form that will input and display the values for the WebsiteUser object we want to manipulate. Each of these will have a ng-model attribute set, which binds it to the value of the attribute:

<table>
    <tr>
        <td width="100">ID:</td>
        <td><input type="text" id="id" ng-model="user.id" /></td>
    </tr>
    <tr>
        <td width="100">Name:</td>
        <td><input type="text" id="name" ng-model="user.name" /></td>
    </tr>
    <tr>
        <td width="100">Age:</td>
        <td><input type="text" id="age" ng-model="user.email" /></td>
    </tr>
</table>

Binding the id input to the user.id variable, for example, means that whenever the value of the input is changed, this value is set in the user.id variable and vice versa.

Next, let’s use the ng-click attribute to define the links that will trigger the invoking of each CRUD controller function defined:

<a ng-click="getUser(user.id)">Get User</a>
<a ng-click="updateUser(user.id,user.name,user.email)">Update User</a>
<a ng-click="addUser(user.name,user.email)">Add User</a>
<a ng-click="deleteUser(user.id)">Delete User</a>

Finally, let’s display the list of users entirely and by name:

<a ng-click="getAllUsers()">Get all Users</a><br/><br/>
<div ng-repeat="usr in users">
{{usr.name}} {{usr.email}}
</div>

4. 結論

在本教程中,我們展示瞭如何使用 AngularJSSpring Data REST 規範創建 CRUD 應用程序。

要運行應用程序,可以使用命令 mvn spring-boot:run 並訪問 URL /users.html

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.