An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
April 18, 2022 03:18 pm GMT
Original Link: https://dev.to/yigi/spring-pathvariable-200o
Spring - @PathVariable
A Spring annotation called @PathVariable specifies that a method parameter should be tied to a URI template variable.
@GetMapping("/api/products/{id}")@ResponseBodypublic String getProductsById(@PathVariable String id) { return "ID: " + id;}
A simple GET request to /api/products/{id} will invoke getProductsById with the extracted id value:
http://localhost:8080/api/products/333 ---- ID: 333
We may also specify the path variable name:
@GetMapping("/api/products/{id}")@ResponseBodypublic String getProductsById(@PathVariable("id") String productId) { return "ID: " + productId;}
One Class to Rule Them All
Best practice to handle not required path variables is to combine with Java Optional. In this way, you are both able to handle exceptions and the logic.
@GetMapping(value = { "/api/products", "/api/products/{id}" })@ResponseBodypublic String getProducts(@PathVariable Optional<String> id) { if (id.isPresent()) { return "ID: " + id.get(); } else { return "ID missing"; }}
Now if we don't specify the path variable id in the request, we get the default response:
http://localhost:8080/api/employeeswithoptional ----ID missing
Original Link: https://dev.to/yigi/spring-pathvariable-200o
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To