पाठ 8 / 25
Request Mapping and Parameters
Paths, query strings and bodies.
@PathVariable, @RequestParam, @RequestBody
@PathVariable reads parts of the URL (/products/{id}), @RequestParam reads query parameters (?max=1000, with conversion to types such as BigDecimal), and @RequestBody deserialises JSON into an object. Conversion errors produce 400 responses automatically. Keep URLs resource-oriented (nouns, plural), use HTTP methods for actions, and limit result sizes; here a configured maximum page size caps the list.
Filtering with a query parameter, run
I packaged the demo with mvn package, started it with java -jar on port 8085 and called it with curl; the output is copied from that run. max=1000 returns the two cheaper products, ordered by price by the repository query.
curl -s "localhost:8085/api/products?max=1000"
Output:
[{"id":1,"name":"Notebook","price":120.00,"currency":"INR"},{"id":2,"name":"Fountain pen","price":899.00,"currency":"INR"}]Always cap list endpoints
Unbounded list endpoints are a performance and denial-of-service risk; enforce a maximum page size.
त्वरित जाँच: Which annotation reads ?max=1000 from the URL?
- @RequestBody
- @PathVariable
- @RequestParam
- @Entity
Answer
@RequestParam — Query parameters map to @RequestParam.