In case you don't want just the total number of the elements in the response but the total number of entities in the corresponding JPA method of PagingAndSortingRepository you can do something like that which is useful for paging applications :)
Inspired by Bohdan's answer ( https://stackoverflow.com/a/44376133/986160)
@ControllerAdvice
public class ResourceSizeAdvice implements ResponseBodyAdvice<Page<?>> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
//Checks if this advice is applicable.
//In this case it applies to any endpoint which returns a page.
return Page.class.isAssignableFrom(returnType.getParameterType());
}
@Override
public Page<?> beforeBodyWrite(Page<?> page, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
serverHttpResponse.getHeaders().add("X-Total-Count",String.valueOf(page.getTotalElements()));
return page;
}
}
Make sure to call the Pageable version of the default methods like so it returns a Page and not a List:
repository.findAll(new PageRequest(0,100));
If you are not using Repositories then you have to do two queries:
Select * from ... and
Select count(*) from ...
and return a Wrapper which has contents for the list of results plus total for the total coming from count. Then you can change the @ControllerAdvice class to expect your Wrapper and get the total from it and put it in the header