Issue
If I have a Get request that returns orders of clients, how can I filter the response to give me the objects that have a specific value for example that are made by those specific clients in Spring Boot? I have tried with @PathVariable and @RequestParams but every attempt failed. Thank you in advance.
Solution
If you want to show a specific order which has an identifier of some sort, use @PathVariable
. In the following example, the identifier is a String
, but in many case it will rather be long or an Integer.
@RestController
@RequestMapping("/orders")
public class OrdersController {
@GetMapping("/{id}")
public Order getOrder(@PathVariable("id") String id) {
// get the order with a specified id from the backend
}
}
The web request in this case will look like http:/<host>:<port>/orders/123
If you want to filter the order by some name, like 'madeBy John', use Request parameter:
@RestController
@RequestMapping("/orders")
public class OrdersController {
@GetMapping("/")
public List<Order> getOrdersFilteredByName(@RequestParam("madeBy") madeBy) {
// get the order filtered by the person who made the order
// note, this one returns the list
}
}
In this case the web request will look like this: http:/<host>:<port>/orders?madeBy=John
Note that technically you can implement whatever you want at the backend, so you can pass, say, John
in the first example as a path variable, on server its a String after all, however what I've described is a straightforward and kind-of-standard way of doing these things - so can expect to see this convention in many projects at least.
Answered By - Mark Bramnik
Answer Checked By - Candace Johnson (JavaFixing Volunteer)