A query string can carry several parameters, joined with &. In /products?category=office&max_price=5 the client asks for office products that cost 5 or less. The order of the parameters doesn't matter, because Spring reads each one by its name.
Not every parameter is a number. A category is text, so its type is String; with required = false, like any optional parameter, it is null when the URL leaves it out. Here is the idea on another route, with two optional parameters:
@GetMapping("/greet")
String greet(@RequestParam(required = false) String name, @RequestParam(required = false) Integer times) {
if (name == null) {
name = "friend";
}
if (times == null) {
times = 1;
}
return ("Hello, " + name + "! ").repeat(times);
}
To combine two filters, put one check inside the other: a product is added only when it passes the price check and the category check. Each check lets every product through when its parameter is null, so each filter also works alone. Java compares texts with .equals, not ==. Your code must give:
GET /products?category=office → 200 [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products?category=office&max_price=5 → 200 [{"id": 4, "name": "Pen", …}]
GET /products?max_price=20&category=kitchen → 200 [{"id": 1, "name": "Mug", …}]
GET /products?category=garden → 200 []
GET /products?category=home&max_price=10 → 200 []
GET /products?max_price=10 → 200 [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products → 200 all 4 products
Your task: give getProducts a second query parameter, category, and change its loop so a product is added only when it passes both filters. Either filter can be left out.
Assignment
Follow the Coding Tutorial to take category and add the category check inside the price check.
Hint
The category check has the same shape as the price check: the null test first, then ||, then a comparison with .equals. The result.add line goes one level deeper, inside the new if.
Free plan: 30 tutor messages. PRO is unlimited.
