Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DataTables - Spring Boot pagination example
package com.dummy.datatables.example;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class DummyController {
Logger log = LoggerFactory.getLogger(DummyController.class);
@Autowired
private DummyRepository dummyRepository; // This should be a @Service not a @Repository, but we just want a simple demonstration.
@GetMapping("/dummy/list-paginated")
public ResponseEntity<?> list(@RequestParam(value = "pageSize", required = false) Optional<Integer> pageSize,
@RequestParam(value = "pageNumber", required = false) Optional<Integer> pageNumber,
@RequestParam(value = "sort", required = false) Sort sort) {
log.info("Listing dummy records with page number:{} and size: {}", pageNumber, pageSize);
// Some response bean to standardise all restful responses.
RestResponseBody result = new RestResponseBody();
try {
// Create page request as Spring uses it to query results while
// taking pagination into account.
PageRequest request = new PageRequest(pageNumber.orElse(0), pageSize.orElse(10), sort);
Page<Dummy> records = dummyRepository.findAll(request);
result.setData(records);
} catch (Exception e) {
log.error("Exception occurred when trying to find records, assuming invalid parameters", e);
result.setMessage(e.getMessage());
return ResponseEntity.badRequest().body(result);
}
return ResponseEntity.ok(result);
}
@GetMapping("/dummy/list")
public String getDummyPage() {
log.info("Getting list page");
return "dummy/list";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment