0 day streak
java / beginner
Snippet

Extracting Primitive Route Values with PathVariable

Spring MVC automatically parses URL path placeholders and converts string tokens into target Java datatypes like Long or boolean. Using @PathVariable binds the dynamic segment directly to strongly-typed method parameters.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
@GetMapping("/products/{id}/active/{flag}")
public String getProductInfo(
@PathVariable("id") Long productId,
@PathVariable("flag") boolean isActive) {
return "Product ID: " + productId + ", Active: " + isActive;
}
}
spring
Breakdown
1
@GetMapping("/products/{id}/active/{flag}")
Defines route template variables inside curly braces within the endpoint mapping.
2
@PathVariable("id") Long productId
Binds the dynamic '{id}' path fragment and automatically converts it into a 64-bit Long.