Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Managing pagination through HTTP headers on Spring Boot. `PageResponseAdvice` intercepts responses in `PageResponse` type and puts pagination related fields into HTTP response headers.
public class PageResponseAdvice implements ResponseBodyAdvice<Object> {
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return PageResponse.class.isAssignableFrom(returnType.getParameterType());
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
PageResponse pageResponse = (PageResponse) body;
response.getHeaders().add("X-Paging-Page", String.valueOf(pageResponse.getPage()));
response.getHeaders().add("X-Paging-Page-Size", String.valueOf(pageResponse.getPageSize()));
response.getHeaders().add("X-Paging-Total-Page", String.valueOf(pageResponse.getTotalPage()));
return pageResponse.getData();
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
public PageResponse<ProductResponse> getProducts(ProductFilterRequest productFilterRequest) {
Page<ProductResponse> products = productService.getProducts(productFilterRequest);
return new PageResponse<>(
public class PageResponse<T> {
private final Integer page;
private final Integer pageSize;
private final Integer totalPage;
private final List<T> data;
public PageResponse(Integer page, Integer pageSize, Integer totalPage, List<T> data) { = page;
this.pageSize = pageSize;
this.totalPage = totalPage; = data;
public Integer getPage() {
return page;
public Integer getPageSize() {
return pageSize;
public Integer getTotalPage() {
return totalPage;
public List<T> getData() {
return data;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment