Paginasi dengan jadual Spring REST dan AngularJS

REST Teratas

Saya baru sahaja mengumumkan kursus Learn Spring yang baru , yang berfokus pada asas-asas Spring 5 dan Spring Boot 2:

>> SEMAK KURSUS

1. Gambaran keseluruhan

Dalam artikel ini, kami terutama akan menumpukan pada pelaksanaan penomboran sisi pelayan dalam Spring REST API dan sudut depan AngularJS yang sederhana.

Kami juga akan meneroka grid meja yang biasa digunakan di Angular bernama UI Grid.

2. Kebergantungan

Di sini kami memperincikan pelbagai kebergantungan yang diperlukan untuk artikel ini.

2.1. JavaScript

Agar Grid UI Angular berfungsi, kami memerlukan skrip di bawah yang diimport dalam HTML kami.

  • JS sudut (1.5.8)
  • Grid UI sudut

2.2. Maven

Untuk backend kami akan menggunakan Spring Boot , jadi kami memerlukan pergantungan di bawah:

 org.springframework.boot spring-boot-starter-web   org.springframework.boot spring-boot-starter-tomcat provided 

Catatan: Pergantungan lain tidak dinyatakan di sini, untuk senarai penuh, periksa pom.xml lengkap dalam projek GitHub.

3. Mengenai Permohonan

Aplikasi ini adalah aplikasi direktori pelajar yang mudah yang membolehkan pengguna melihat butiran pelajar di grid jadual yang dihiasi.

Aplikasi ini menggunakan Spring Boot dan berjalan di pelayan Tomcat tertanam dengan pangkalan data terbenam.

Akhirnya, di sisi API, terdapat beberapa cara untuk melakukan penomboran, yang dijelaskan dalam artikel REST Pagination in Spring di sini - yang sangat disarankan membaca bersama dengan artikel ini.

Penyelesaian kami di sini adalah mudah - mempunyai maklumat paging dalam pertanyaan URI seperti berikut: / student / get? Page = 1 & size = 2 .

4. Bahagian Pelanggan

Pertama, kita perlu membuat logik sisi pelanggan.

4.1. UI-Grid

Index.html kami akan mempunyai import yang kami perlukan dan pelaksanaan grid grid yang mudah:

Mari kita perhatikan kodnya dengan lebih dekat:

  • ng-app - adalah arahan Sudut yang memuat aplikasi modul . Semua elemen di bawah ini akan menjadi sebahagian daripada modul aplikasi
  • ng-pengawal - adalah arahan Sudut yang memuatkan pengawal StudentCtrl dengan alias vm. Semua elemen di bawah ini akan menjadi sebahagian daripada pengawal StudentCtrl
  • ui-grid - adalah arahan Angular yang dimiliki oleh sudut ui-grid dan menggunakan gridOptions sebagai tetapan lalai, gridOptions dinyatakan di bawah $ lingkup di app.js

4.2. Modul AngularJS

Mari tentukan terlebih dahulu modul di app.js :

var app = angular.module('app', ['ui.grid','ui.grid.pagination']);

Kami menyatakan modul aplikasi dan kami memasukkan ui.grid untuk mengaktifkan fungsi UI-Grid; kami juga menyuntik ui.grid.pagination untuk membolehkan sokongan penomboran.

Seterusnya, kami akan menentukan pengawal:

app.controller('StudentCtrl', ['$scope','StudentService', function ($scope, StudentService) { var paginationOptions = { pageNumber: 1, pageSize: 5, sort: null }; StudentService.getStudents( paginationOptions.pageNumber, paginationOptions.pageSize).success(function(data){ $scope.gridOptions.data = data.content; $scope.gridOptions.totalItems = data.totalElements; }); $scope.gridOptions = { paginationPageSizes: [5, 10, 20], paginationPageSize: paginationOptions.pageSize, enableColumnMenus:false, useExternalPagination: true, columnDefs: [ { name: 'id' }, { name: 'name' }, { name: 'gender' }, { name: 'age' } ], onRegisterApi: function(gridApi) { $scope.gridApi = gridApi; gridApi.pagination.on.paginationChanged( $scope, function (newPage, pageSize) { paginationOptions.pageNumber = newPage; paginationOptions.pageSize = pageSize; StudentService.getStudents(newPage,pageSize) .success(function(data){ $scope.gridOptions.data = data.content; $scope.gridOptions.totalItems = data.totalElements; }); }); } }; }]); 

Sekarang mari kita lihat tetapan penomboran khas di $ lingkup.gridOptions :

  • paginationPageSizes - menentukan pilihan ukuran halaman yang tersedia
  • paginationPageSize – defines the default page size
  • enableColumnMenus – is used to enable/disable the menu on columns
  • useExternalPagination – is required if you are paginating on the server side
  • columnDefs – the column names that will be automatically mapped to the JSON object returned from the server. The field names in the JSON Object returned from the server and the column name defined should match.
  • onRegisterApi – the ability to register public methods events inside the grid. Here we registered the gridApi.pagination.on.paginationChanged to tell UI-Grid to trigger this function whenever the page was changed.

And to send the request to the API:

app.service('StudentService',['$http', function ($http) { function getStudents(pageNumber,size) { pageNumber = pageNumber > 0?pageNumber - 1:0; return $http({ method: 'GET', url: 'student/get?page='+pageNumber+'&size='+size }); } return { getStudents: getStudents }; }]);

5. The Backend and the API

5.1. The RESTful Service

Here's the simple RESTful API implementation with pagination support:

@RestController public class StudentDirectoryRestController { @Autowired private StudentService service; @RequestMapping( value = "/student/get", params = { "page", "size" }, method = RequestMethod.GET ) public Page findPaginated( @RequestParam("page") int page, @RequestParam("size") int size) { Page resultPage = service.findPaginated(page, size); if (page > resultPage.getTotalPages()) { throw new MyResourceNotFoundException(); } return resultPage; } }

The @RestController was introduced in Spring 4.0 as a convenience annotation which implicitly declares @Controller and @ResponseBody.

For our API, we declared it to accept two parameters which are page and size that would also determine the number of records to return to the client.

We also added a simple validation that will throw a MyResourceNotFoundException if the page number is higher than the total pages.

Finally, we'll return Page as the Response – this is a super helpful component of Spring Data which has held pagination data.

5.2. The Service Implementation

Our service will simply return the records based on page and size provided by the controller:

@Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository dao; @Override public Page findPaginated(int page, int size) { return dao.findAll(new PageRequest(page, size)); } } 

5.3. The Repository Implementation

For our persistence layer, we're using an embedded database and Spring Data JPA.

First, we need to setup our persistence config:

@EnableJpaRepositories("com.baeldung.web.dao") @ComponentScan(basePackages = { "com.baeldung.web" }) @EntityScan("com.baeldung.web.entity") @Configuration public class PersistenceConfig { @Bean public JdbcTemplate getJdbcTemplate() { return new JdbcTemplate(dataSource()); } @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); EmbeddedDatabase db = builder .setType(EmbeddedDatabaseType.HSQL) .addScript("db/sql/data.sql") .build(); return db; } } 

The persistence config is simple – we have @EnableJpaRepositories to scan the specified package and find our Spring Data JPA repository interfaces.

We have the @ComponentScan here to automatically scan for all beans and we have @EntityScan (from Spring Boot) to scan for entity classes.

We also declared our simple datasource – using an embedded database that will run the SQL script provided on startup.

Now it's time we create our data repository:

public interface StudentRepository extends JpaRepository {} 

This is basically all that we need to do here; if you want to go deeper into how to set up and use the highly powerful Spring Data JPA, definitely read the guide to it here.

6. Pagination Request and Response

When calling the API – //localhost:8080/student/get?page=1&size=5, the JSON response will look something like this:

{ "content":[ {"studentId":"1","name":"Bryan","gender":"Male","age":20}, {"studentId":"2","name":"Ben","gender":"Male","age":22}, {"studentId":"3","name":"Lisa","gender":"Female","age":24}, {"studentId":"4","name":"Sarah","gender":"Female","age":26}, {"studentId":"5","name":"Jay","gender":"Male","age":20} ], "last":false, "totalElements":20, "totalPages":4, "size":5, "number":0, "sort":null, "first":true, "numberOfElements":5 } 

One thing to notice here is that server returns a org.springframework.data.domain.Page DTO, wrapping our Student Resources.

The Page object will have the following fields:

  • last – set to true if its the last page otherwise false
  • first – set to true if it's the first page otherwise false
  • totalElements – the total number of rows/records. In our example, we passed this to the ui-grid options $scope.gridOptions.totalItems to determine how many pages will be available
  • totalPages – the total number of pages which was derived from (totalElements / size)
  • size – the number of records per page, this was passed from the client via param size
  • number – the page number sent by the client, in our response the number is 0 because in our backend we are using an array of Students which is a zero-based index, so in our backend, we decrement the page number by 1
  • sort – the sorting parameter for the page
  • numberOfElements – the number of rows/records return for the page

7. Testing Pagination

Let's now set up a test for our pagination logic, using RestAssured; to learn more about RestAssured you can have a look at this tutorial.

7.1. Preparing the Test

For ease of development of our test class we will be adding the static imports:

io.restassured.RestAssured.* io.restassured.matcher.RestAssuredMatchers.* org.hamcrest.Matchers.*

Next, we'll set up the Spring enabled test:

@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:8888") 

The @SpringApplicationConfiguration helps Spring know how to load the ApplicationContext, in this case, we used the Application.java to configure our ApplicationContext.

The @WebAppConfiguration was defined to tell Spring that the ApplicationContext to be loaded should be a WebApplicationContext.

And the @IntegrationTest was defined to trigger the application startup when running the test, this makes our REST services available for testing.

7.2. The Tests

Here is our first test case:

@Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { given().params("page", "0", "size", "2").get(ENDPOINT) .then() .assertThat().body("content.name", hasItems("Bryan", "Ben")); } 

This test case above is to test that when page 1 and size 2 is passed to the REST service the JSON content returned from the server should have the names Bryan and Ben.

Let's dissect the test case:

  • given – the part of RestAssured and is used to start building the request, you can also use with()
  • get – the part of RestAssured and if used triggers a get request, use post() for post request
  • hasItems – the part of hamcrest that checks if the values have any match

We add a few more test cases:

@Test public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { given().params("page", "0", "size", "2").get(ENDPOINT) .then() .statusCode(200); }

This test asserts that when the point is actually called an OK response is received:

@Test public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { given().params("page", "0", "size", "2").get(ENDPOINT) .then() .assertThat().body("numberOfElements", equalTo(2)); }

This test asserts that when page size of two is requested the pages size that is returned is actually two:

@Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { given().params("page", "0", "size", "2").get(ENDPOINT) .then() .assertThat().body("first", equalTo(true)); } 

This test asserts that when the resources are called the first time the first page name value is true.

There are many more tests in the repository, so definitely have a look at the GitHub project.

8. Conclusion

This article illustrated how to implement a data table grid using UI-Grid in AngularJS and how to implement the required server side pagination.

Pelaksanaan contoh dan ujian ini boleh didapati dalam projek GitHub. Ini adalah projek Maven, jadi mudah untuk diimport dan dijalankan sebagaimana adanya.

Untuk menjalankan projek boot Spring, anda boleh melakukan mvn spring-boot: run dan mengaksesnya secara tempatan di // localhost: 8080 /.

REST bawah

Saya baru sahaja mengumumkan kursus Learn Spring yang baru , yang berfokus pada asas-asas Spring 5 dan Spring Boot 2:

>> SEMAK KURSUS