0
0
Spring Bootframework~5 mins

Handling path variables and query params together in Spring Boot

Choose your learning style9 modes available
Introduction

We use path variables and query parameters together to get specific and flexible information from a web request. Path variables identify a resource, and query parameters filter or add details.

When you want to get a user by ID and also filter their posts by date.
When you need to fetch a product by its category and sort the results by price.
When you want to access a blog post by its slug and specify the number of comments to show.
When you want to get details of an order by order number and include optional status filters.
Syntax
Spring Boot
@GetMapping("/resource/{id}")
public ResponseEntity<?> methodName(@PathVariable Type id, @RequestParam(required = false) Type param) {
    // method body
}

@PathVariable extracts values from the URL path.

@RequestParam extracts query parameters from the URL after the question mark.

Examples
This method gets a user ID from the path and an optional filter from the query string.
Spring Boot
@GetMapping("/users/{userId}")
public String getUser(@PathVariable String userId, @RequestParam(required = false) String filter) {
    return "User: " + userId + ", Filter: " + filter;
}
This method gets a product category from the path and a sort order from the query, defaulting to ascending.
Spring Boot
@GetMapping("/products/{category}")
public String getProducts(@PathVariable String category, @RequestParam(defaultValue = "asc") String sort) {
    return "Category: " + category + ", Sort: " + sort;
}
Sample Program

This Spring Boot controller has a method that takes an item ID from the URL path and an optional color from the query parameters. It returns a simple string showing both values.

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

@RestController
public class ItemController {

    @GetMapping("/items/{itemId}")
    public String getItemDetails(@PathVariable String itemId, @RequestParam(required = false) String color) {
        if (color == null) {
            return "Item ID: " + itemId + ", Color: not specified";
        }
        return "Item ID: " + itemId + ", Color: " + color;
    }
}
OutputSuccess
Important Notes

If a query parameter is optional, set required = false to avoid errors when it's missing.

You can provide default values for query parameters using defaultValue in @RequestParam.

Path variables are part of the URL structure, while query parameters come after a question mark and can be many or none.

Summary

Use @PathVariable to get parts of the URL path.

Use @RequestParam to get query parameters after the URL path.

Combining both lets you build flexible and clear web endpoints.