Skip to content

Instantly share code, notes, and snippets.

Embed
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.
@ControllerAdvice
public class PageResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return PageResponse.class.isAssignableFrom(returnType.getParameterType());
}
@Override
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();
}
}
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService productService;
@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public PageResponse<ProductResponse> getProducts(ProductFilterRequest productFilterRequest) {
Page<ProductResponse> products = productService.getProducts(productFilterRequest);
return new PageResponse<>(
productFilterRequest.getPage(),
productFilterRequest.getPageSize(),
products.getTotalPages(),
products.getContent()
);
}
}
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) {
this.page = page;
this.pageSize = pageSize;
this.totalPage = totalPage;
this.data = 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
You can’t perform that action at this time.