Pagination with Spring-Data : PageRequest leaking into REST ControllerBest Practices for securing a REST API / web serviceRESTful AuthenticationPagination in a REST web applicationREST HTTP status codes for failed validation or invalid duplicatePosting a File and Associated Data to a RESTful WebService preferably as JSONHow to solve “Plugin execution not covered by lifecycle configuration” for Spring Data Maven BuildsHow do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?REST API response describing request and returned dataHow to prevent shifting of paged data in a REST API result set

I reverse the source code, you negate the output!

Would Taiwan and China's dispute be solved if Taiwan gave up being the Republic of China?

Leaving a job that I just took based on false promise of a raise. What do I tell future interviewers?

Did Apollo carry and use WD40?

Do the villains know Batman has no superpowers?

An Algorithm Which Schedules Your Life

How to manage expenditure when billing cycles and paycheck cycles are not aligned?

How much Damage can be done with "just" heating matter?

Writing a letter of recommendation for a mediocre student

Examples of "unsuccessful" theories with afterlives

What happens if nobody can form a government in Israel?

Where are they calling from?

Will Proving or Disproving of any of the following have effects on Chemistry in general?

Is it impolite to ask for halal food when traveling to and in Thailand?

What benefits does the Power Word Kill spell have?

What was the deeper meaning of Hermione wanting the cloak?

Safely hang a mirror that does not have hooks

Resolving moral conflict

Do you need to hold concentration on a spell when you cast it with a spell scroll?

Is it more effective to add yeast before or after kneading?

Allocating credit card points

How can I repair this gas leak on my new range? Teflon tape isn't working

Is it true that, "just ten trading days represent 63 per cent of the returns of the past 50 years"?

What is this utensil for?



Pagination with Spring-Data : PageRequest leaking into REST Controller


Best Practices for securing a REST API / web serviceRESTful AuthenticationPagination in a REST web applicationREST HTTP status codes for failed validation or invalid duplicatePosting a File and Associated Data to a RESTful WebService preferably as JSONHow to solve “Plugin execution not covered by lifecycle configuration” for Spring Data Maven BuildsHow do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?REST API response describing request and returned dataHow to prevent shifting of paged data in a REST API result set






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm working on a REST API based on Spring-Boot with a MongoDB database. The application uses a Controller > Service > Repository approach. I'm currently working on implementing a paginated endpoint:



/api/clients?range=offset-limit

eg. /api/clients?range=0-25 (retrieves entities 0-24)


My problem is that, in order to build a 'Content Range' response and in order to distinguish between 200 'OK' and 206 'Partial Content' responses (depending on whether the request retrieves all the entities or not), I need to retrieve info like the total number of entities from a Page object. So I'm building a PageRequest in the Controller which gets passed to the Service and through to the Repository. I end up with something along these lines :



@ResponseBody
@GetMapping(params = "range" )
public ResponseEntity<?> getAllClients(
final @RequestParam(value = "range", required = false) QueryRange queryRange,
final HttpServletResponse response)

response.addHeader(HttpHeaders.ACCEPT_RANGES, "client " + MAX_CLIENTS);

if (queryRange.getCount() > MAX_CLIENTS)
throw new ForbiddenRangeException("client", MAX_CLIENTS);


Integer offset = queryRange.getOffset();
Integer limit = queryRange.getLimit();

Integer count = limit - offset;
Integer page = offset != 0 ? offset / count : 0;

PageRequest request = PageRequest.of(page, count);

final Page<Client> clients = clientService.getAllClients(request);

final HttpStatus status = (queryRange.getOffset() == 0 && clients.isLast())
? HttpStatus.OK
: HttpStatus.PARTIAL_CONTENT;

final String contentRange = String.format("%d-%d/%d",
queryRange.getOffset(),
queryRange.getOffset() + clients.getContent().size() - 1,
clients.getTotalElements());

response.addHeader(HttpHeaders.CONTENT_RANGE, contentRange);

return new ResponseEntity<>(clients, status);



How could one structure this in order to prevent such leaking ?



Any ideas?










share|improve this question


























  • What is the question?

    – Oliver Drotbohm
    Mar 29 at 6:38











  • I've amended the original question. Basically, in this use case is there a way to avoid spring-data concepts such as Pageable from leaking all the way up to the controller ?

    – Anthony Webster
    Mar 29 at 10:55

















0















I'm working on a REST API based on Spring-Boot with a MongoDB database. The application uses a Controller > Service > Repository approach. I'm currently working on implementing a paginated endpoint:



/api/clients?range=offset-limit

eg. /api/clients?range=0-25 (retrieves entities 0-24)


My problem is that, in order to build a 'Content Range' response and in order to distinguish between 200 'OK' and 206 'Partial Content' responses (depending on whether the request retrieves all the entities or not), I need to retrieve info like the total number of entities from a Page object. So I'm building a PageRequest in the Controller which gets passed to the Service and through to the Repository. I end up with something along these lines :



@ResponseBody
@GetMapping(params = "range" )
public ResponseEntity<?> getAllClients(
final @RequestParam(value = "range", required = false) QueryRange queryRange,
final HttpServletResponse response)

response.addHeader(HttpHeaders.ACCEPT_RANGES, "client " + MAX_CLIENTS);

if (queryRange.getCount() > MAX_CLIENTS)
throw new ForbiddenRangeException("client", MAX_CLIENTS);


Integer offset = queryRange.getOffset();
Integer limit = queryRange.getLimit();

Integer count = limit - offset;
Integer page = offset != 0 ? offset / count : 0;

PageRequest request = PageRequest.of(page, count);

final Page<Client> clients = clientService.getAllClients(request);

final HttpStatus status = (queryRange.getOffset() == 0 && clients.isLast())
? HttpStatus.OK
: HttpStatus.PARTIAL_CONTENT;

final String contentRange = String.format("%d-%d/%d",
queryRange.getOffset(),
queryRange.getOffset() + clients.getContent().size() - 1,
clients.getTotalElements());

response.addHeader(HttpHeaders.CONTENT_RANGE, contentRange);

return new ResponseEntity<>(clients, status);



How could one structure this in order to prevent such leaking ?



Any ideas?










share|improve this question


























  • What is the question?

    – Oliver Drotbohm
    Mar 29 at 6:38











  • I've amended the original question. Basically, in this use case is there a way to avoid spring-data concepts such as Pageable from leaking all the way up to the controller ?

    – Anthony Webster
    Mar 29 at 10:55













0












0








0


1






I'm working on a REST API based on Spring-Boot with a MongoDB database. The application uses a Controller > Service > Repository approach. I'm currently working on implementing a paginated endpoint:



/api/clients?range=offset-limit

eg. /api/clients?range=0-25 (retrieves entities 0-24)


My problem is that, in order to build a 'Content Range' response and in order to distinguish between 200 'OK' and 206 'Partial Content' responses (depending on whether the request retrieves all the entities or not), I need to retrieve info like the total number of entities from a Page object. So I'm building a PageRequest in the Controller which gets passed to the Service and through to the Repository. I end up with something along these lines :



@ResponseBody
@GetMapping(params = "range" )
public ResponseEntity<?> getAllClients(
final @RequestParam(value = "range", required = false) QueryRange queryRange,
final HttpServletResponse response)

response.addHeader(HttpHeaders.ACCEPT_RANGES, "client " + MAX_CLIENTS);

if (queryRange.getCount() > MAX_CLIENTS)
throw new ForbiddenRangeException("client", MAX_CLIENTS);


Integer offset = queryRange.getOffset();
Integer limit = queryRange.getLimit();

Integer count = limit - offset;
Integer page = offset != 0 ? offset / count : 0;

PageRequest request = PageRequest.of(page, count);

final Page<Client> clients = clientService.getAllClients(request);

final HttpStatus status = (queryRange.getOffset() == 0 && clients.isLast())
? HttpStatus.OK
: HttpStatus.PARTIAL_CONTENT;

final String contentRange = String.format("%d-%d/%d",
queryRange.getOffset(),
queryRange.getOffset() + clients.getContent().size() - 1,
clients.getTotalElements());

response.addHeader(HttpHeaders.CONTENT_RANGE, contentRange);

return new ResponseEntity<>(clients, status);



How could one structure this in order to prevent such leaking ?



Any ideas?










share|improve this question
















I'm working on a REST API based on Spring-Boot with a MongoDB database. The application uses a Controller > Service > Repository approach. I'm currently working on implementing a paginated endpoint:



/api/clients?range=offset-limit

eg. /api/clients?range=0-25 (retrieves entities 0-24)


My problem is that, in order to build a 'Content Range' response and in order to distinguish between 200 'OK' and 206 'Partial Content' responses (depending on whether the request retrieves all the entities or not), I need to retrieve info like the total number of entities from a Page object. So I'm building a PageRequest in the Controller which gets passed to the Service and through to the Repository. I end up with something along these lines :



@ResponseBody
@GetMapping(params = "range" )
public ResponseEntity<?> getAllClients(
final @RequestParam(value = "range", required = false) QueryRange queryRange,
final HttpServletResponse response)

response.addHeader(HttpHeaders.ACCEPT_RANGES, "client " + MAX_CLIENTS);

if (queryRange.getCount() > MAX_CLIENTS)
throw new ForbiddenRangeException("client", MAX_CLIENTS);


Integer offset = queryRange.getOffset();
Integer limit = queryRange.getLimit();

Integer count = limit - offset;
Integer page = offset != 0 ? offset / count : 0;

PageRequest request = PageRequest.of(page, count);

final Page<Client> clients = clientService.getAllClients(request);

final HttpStatus status = (queryRange.getOffset() == 0 && clients.isLast())
? HttpStatus.OK
: HttpStatus.PARTIAL_CONTENT;

final String contentRange = String.format("%d-%d/%d",
queryRange.getOffset(),
queryRange.getOffset() + clients.getContent().size() - 1,
clients.getTotalElements());

response.addHeader(HttpHeaders.CONTENT_RANGE, contentRange);

return new ResponseEntity<>(clients, status);



How could one structure this in order to prevent such leaking ?



Any ideas?







mongodb rest spring-boot spring-data






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 29 at 9:49







Anthony Webster

















asked Mar 28 at 15:38









Anthony WebsterAnthony Webster

793 silver badges11 bronze badges




793 silver badges11 bronze badges















  • What is the question?

    – Oliver Drotbohm
    Mar 29 at 6:38











  • I've amended the original question. Basically, in this use case is there a way to avoid spring-data concepts such as Pageable from leaking all the way up to the controller ?

    – Anthony Webster
    Mar 29 at 10:55

















  • What is the question?

    – Oliver Drotbohm
    Mar 29 at 6:38











  • I've amended the original question. Basically, in this use case is there a way to avoid spring-data concepts such as Pageable from leaking all the way up to the controller ?

    – Anthony Webster
    Mar 29 at 10:55
















What is the question?

– Oliver Drotbohm
Mar 29 at 6:38





What is the question?

– Oliver Drotbohm
Mar 29 at 6:38













I've amended the original question. Basically, in this use case is there a way to avoid spring-data concepts such as Pageable from leaking all the way up to the controller ?

– Anthony Webster
Mar 29 at 10:55





I've amended the original question. Basically, in this use case is there a way to avoid spring-data concepts such as Pageable from leaking all the way up to the controller ?

– Anthony Webster
Mar 29 at 10:55












0






active

oldest

votes














Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55401589%2fpagination-with-spring-data-pagerequest-leaking-into-rest-controller%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55401589%2fpagination-with-spring-data-pagerequest-leaking-into-rest-controller%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해