Look down, at the end of this answer, for the better solution.
The best approach is following the single responsibility pattern.
As your URL could be called using two different ways, why not splitting it, and letting each one implement its own logic?
@GetMapping
public ResponseEntity<?> getAllTasks() {
return ResponseEntity.ok().body(this.taskResource.findAll());
}
@GetMapping
public ResponseEntity<?> getAllTasksWithStatus(@RequestParam("status") final int status) {
return ResponseEntity.ok().body(this.tacheResource.getTachesByEtat(status));
}
Spring will handle this beautifully.
Note that when you use a single, value
property with an Annotation
, you don't need to explicitly specify it.
Edit: being that this can have the effect of producing a mapping collision, an even better alternative to @RequestParam
is using @PathVariable
for the *WithStatus
endpoint.
@GetMapping("/status/{status}")
public ResponseEntity<?> getAllTasksWithStatus(@PathVariable("status") final int status) {
return ResponseEntity.ok().body(this.tacheResource.getTachesByEtat(status));
}
When dealing with complex, long, URLs, there are two roads to take.
Use @PathVariable
(s), such as
/{status}/{date}/{name}
Or go for a POST
HTTP request. Here you can customize the body
as you prefer. I usually go for POST requests when dealing with complex HTTP calls.
Last edit, hopefully:
you can narrow down mapping by specifying the wanted query params.
@GetMapping
public ResponseEntity<?> getAllTasks() {
return ResponseEntity.ok().body(this.taskResource.findAll());
}
@GetMapping(params = "status")
public ResponseEntity<?> getAllTasksWithStatus(@RequestParam("status") final int status) {
return ResponseEntity.ok().body(this.tacheResource.getTachesByEtat(status));
}
No more conflicts ;)
As params
is an array, you can specify multiple values with
@GetMapping(params = { "status", "date" })