You are currently viewing Understanding Spring @RequestParam vs @PathVariable

Understanding Spring @RequestParam vs @PathVariable

In Spring MVC, @RequestParam and @PathVariable are two commonly used annotations for handling incoming requests and extracting data from the URL. While they might seem similar, they serve different purposes and are used in distinct scenarios. In this tutorial, we’ll explore the differences between @RequestParam and @PathVariable with examples to illustrate their usage.

@RequestParam Annotation

The @RequestParam annotation is used to extract query parameters from the request URL. Query parameters are the key-value pairs that come after the question mark (?) in a URL. These parameters are optional and are often used for filtering, sorting, or passing additional data to the server.

Example:

Let’s consider a simple Spring MVC controller that handles a request with query parameters:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/user")
    public String getUserById(@RequestParam("id") Long userId) {
        return "User ID: " + userId;
    }
}

In this example:

  • The @GetMapping("/user") annotation maps the method to handle requests to the /user endpoint.
  • The @RequestParam("id") Long userId annotation binds the id query parameter from the request URL to the userId parameter of the getUserById method.

Request URL:

http://localhost:8080/user?id=123

Output:

User ID: 123

Here, the id=123 is the query parameter, and @RequestParam helps us extract this value and use it in our controller method.

@PathVariable Annotation

The @PathVariable annotation, on the other hand, is used to extract values from the URI itself. Unlike query parameters, path variables are a part of the URI path itself and are used to identify a specific resource or entity.

Example:

Let’s create a controller that uses @PathVariable to retrieve a user’s details based on their ID:

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 Long id) {
        return "User ID: " + id;
    }
}

In this example:

  • The @GetMapping("/user/{id}") annotation maps the method to handle requests to the /user/{id} endpoint, where {id} is a path variable.
  • The @PathVariable Long id annotation extracts the id path variable from the URI and binds it to the id parameter of the getUserById method.

Request URL:

http://localhost:8080/user/456

Output:

User ID: 456

Here, 456 is the id path variable, and @PathVariable helps us extract this value from the URI.

When to Use @RequestParam vs @PathVariable

  • Use @RequestParam when dealing with optional parameters in the URL, typically for filtering, sorting, or passing additional data.
  • Use @PathVariable when the parameter is part of the resource’s path and is required to identify a specific resource.

Combining @RequestParam and @PathVariable

It’s also common to use both annotations together. For example, consider a scenario where we want to retrieve a specific user’s details by ID but also allow optional filtering by username:

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 UserController {

    @GetMapping("/user/{id}")
    public String getUserById(
            @PathVariable Long id,
            @RequestParam(name = "username", required = false) String username) {

        if (username != null) {
            return "User ID: " + id + ", Username: " + username;
        } else {
            return "User ID: " + id;
        }
    }
}

Request URLs:

  • http://localhost:8080/user/123
  • Output: User ID: 123
  • http://localhost:8080/user/123?username=johndoe
  • Output: User ID: 123, Username: johndoe

In this example, we have combined @PathVariable and @RequestParam to handle both the required id path variable and an optional username query parameter.

Conclusion

In summary, @RequestParam and @PathVariable are essential annotations in Spring MVC for extracting data from incoming requests. Remember:

  • Use @RequestParam for query parameters in the URL.
  • Use @PathVariable for path variables in the URI path.
  • You can combine both annotations for more complex scenarios where you need to handle both path variables and query parameters.

Understanding when to use each annotation will help you build more effective and expressive Spring MVC controllers for your web applications.

Leave a Reply