0
0
Spring Bootframework~5 mins

@PathVariable for URL parameters in Spring Boot

Choose your learning style9 modes available
Introduction

@PathVariable lets you get parts of the URL as variables in your code. This helps your app respond differently based on the URL.

When you want to get an ID from the URL, like /user/123 to find user 123.
When you want to handle URLs with changing parts, like /product/phone or /product/laptop.
When building REST APIs that use URLs to specify resources.
When you want clean URLs that are easy to read and understand.
When you want to avoid using query parameters for simple data in the URL path.
Syntax
Spring Boot
@GetMapping("/path/{variableName}")
public ReturnType methodName(@PathVariable Type variableName) {
    // use variableName here
}

The part in curly braces {} in the URL is the variable name.

The method parameter annotated with @PathVariable must match the variable name in the URL.

Examples
This gets the 'id' from the URL like /user/123 and returns it.
Spring Boot
@GetMapping("/user/{id}")
public String getUser(@PathVariable String id) {
    return "User ID: " + id;
}
This gets two variables from the URL, orderId and itemId.
Spring Boot
@GetMapping("/order/{orderId}/item/{itemId}")
public String getOrderItem(@PathVariable int orderId, @PathVariable int itemId) {
    return "Order: " + orderId + ", Item: " + itemId;
}
You can specify the variable name explicitly in @PathVariable(name = "name") if the method parameter name is different.
Spring Boot
@GetMapping("/product/{name}")
public String getProduct(@PathVariable(name = "name") String productName) {
    return "Product: " + productName;
}
Sample Program

This simple Spring Boot controller has one URL endpoint /user/{id}. When you visit /user/45, it returns 'User ID received: 45'.

Spring Boot
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable String id) {
        return "User ID received: " + id;
    }
}
OutputSuccess
Important Notes

If the method parameter name matches the path variable name, you can omit the name attribute in @PathVariable.

Path variables are always strings but Spring can convert them to other types like int or long automatically.

Use @PathVariable only for parts of the URL path, not for query parameters (use @RequestParam for those).

Summary

@PathVariable extracts values from the URL path.

It helps create dynamic and readable URLs.

Use it in Spring Boot controller methods with @GetMapping or other mapping annotations.