Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 18, 2022 03:18 pm GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To