CodeGym /Courses /Module 5. Spring /Working with requests: @PathVariable, @RequestParam

Working with requests: @PathVariable, @RequestParam

Module 5. Spring
Level 7 , Lesson 3
Available

Now we're moving to an important part of working with requests — their parameters. In this lecture we'll walk through how to extract values from the URL (path variables) and how to handle request parameters (request parameters). These two techniques are the foundation for building flexible and practical web apps.


What are request parameters and why you need them

When a user sends a request to the server (for example, to find a specific article or a user profile), data can be sent with the request. That data can be part of the URL or sent as parameters in the query string. Spring MVC gives a simple and powerful way to extract this data using the annotations @PathVariable and @RequestParam.

But why would you need this at all? Well, imagine instead of a generic response like "all articles", you want to show a specific article by its id (for example, /articles/42). Or, say, find products by category with a certain filter (for example, /products?category=books&sort=price-desc). In both cases we need to handle request parameters to give the user the data they asked for.


Handling path variables: the @PathVariable annotation

Let's start with @PathVariable. This annotation is used to pull values straight from the URI (URL). It lets you define dynamic parts of a route.

Usage example

Say you want to show a user's profile by their ID. The URL could look like /users/123. Here 123 is the path variable value.

Code example:


@RestController
@RequestMapping("/users")
public class UserController {

    // Handle a request like /users/123
    @GetMapping("/{id}")
    public String getUserById(@PathVariable("id") Long userId) {
        // Here we can use userId to look up the user
        return "User with ID: " + userId;
    }
}

Key points:

  • The @PathVariable annotation binds a value from the URL to a method variable.
  • In the route we declare the dynamic part of the path: {id}.
  • In the controller method we use the userId variable to handle the request.

For GET /users/123 the server will return: User with ID: 123.

A slightly more complex example

You can use multiple variables in the path:


@RestController
@RequestMapping("/articles")
public class ArticleController {

    @GetMapping("/{category}/{id}")
    public String getArticleByCategoryAndId(@PathVariable String category, @PathVariable Long id) {
        return "Article from category '" + category + "' with ID: " + id;
    }
}

Now a request GET /articles/tech/42 will return: Article from category 'tech' with ID: 42.


How parameters get into the request: the @RequestParam annotation

If you need to extract data from the query string, use the @RequestParam annotation. Parameters are passed in the URL after the ? as key=value. For example, /products?category=books.

Usage example

Let's create a method to search for products:


@RestController
@RequestMapping("/products")
public class ProductController {

    @GetMapping("/search")
    public String searchProducts(@RequestParam String category, @RequestParam(defaultValue = "price-asc") String sort) {
        return "Searching products in category: " + category + ", sort: " + sort;
    }
}

Now a request GET /products/search?category=electronics&sort=price-desc will return: Searching products in category: electronics, sort: price-desc.

Key points:

  • The @RequestParam annotation extracts values from the query string.
  • The category field is required, while sort has a default value price-asc.

Handling optional parameters

You can make some parameters optional:


@RestController
@RequestMapping("/products")
public class OptionalParamController {

    @GetMapping("/filter")
    public String filterProducts(@RequestParam(required = false) String category) {
        if (category == null) {
            return "Please choose a category!";
        }
        return "Filtering products by category: " + category;
    }
}

If the request comes without the category parameter, the app will handle it gracefully and return: Please choose a category!.


Comparing @PathVariable and @RequestParam

Characteristic @PathVariable @RequestParam
Data source URL path Query string
Example /users/123 /search?category=books
Annotation @PathVariable("name") @RequestParam("name")
Required Usually required Can be optional
Use case Unique resources (e.g. ID) Filters, sorting, extra options

Example: combining @PathVariable and @RequestParam

Let's look at an example that uses both annotations:


@RestController
@RequestMapping("/orders")
public class OrderController {

    @GetMapping("/{orderId}")
    public String getOrderDetails(@PathVariable Long orderId,
                                   @RequestParam(required = false) String includeDetails) {
        if ("true".equals(includeDetails)) {
            return "Order details with ID: " + orderId + ". Info: [order details]";
        }
        return "Order with ID: " + orderId;
    }
}

Request GET /orders/99?includeDetails=true will return: Order details with ID: 99. Info: [order details].

Request GET /orders/99 will return: Order with ID: 99.


Common mistakes

Errors when using @PathVariable and @RequestParam usually come from mismatched variable names, missing values, wrong required settings, or incorrect types.

For example:

  1. If you use a wrong variable name in the route (/{id}) and in the annotation (@PathVariable("userId")), Spring will throw an exception.
  2. If a request parameter is marked as required but isn't sent by the client, you'll get a 400 Bad Request error.
  3. Wrong data type (for example, trying to pass a string where Long is expected) will lead to an HttpMessageNotReadableException.

How to fix errors

  • Use the same names for variables in the route and annotations.
  • Remember that for @RequestParam you can set a default value via defaultValue.
  • Be careful with data types: if a Long is expected but a string is passed, you'll get an error.

Now you're armed with the knowledge of how to work with request parameters in Spring MVC. This opens up a lot of possibilities for creating flexible routes and handling complex web requests! In the next lectures you'll learn data validation when working with requests and see how Spring MVC helps avoid common mistakes.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION