Difference RequestParam and PathVariable
`@RequestParam`:
The `@RequestParam` annotation is used to extract query parameters from the URL of an HTTP request. It is commonly used to retrieve values from the query string or form data.
- Usage: Typically used for optional or default parameters in a URL. It is commonly used in form submissions or when data is passed in the query string of the URL.
- Scope: Works with query parameters, form data, and URL parameters.
`@PathVariable`:
The `@PathVariable` annotation is used to extract values from URI template variables. It is used when you want to capture values from the URL path.
- Usage: Typically used to extract values from the URL path that are part of the URI template. It is often used for RESTful services where resources are identified by path segments.
- Scope: Works with path segments in the URL.
Table of Contents
Using
RequestParam
1. Using `@RequestParam`
Example: Handling Query Parameters
UserController.java
```java
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 getUser(@RequestParam(name = "id", defaultValue = "1") Long userId,
@RequestParam(name = "name", required = false) String username) {
return "User ID: " + userId + ", Username: " + username;
}
}
```
Example URL: `/user?id=123&name=JohnDoe`
In this example:
@RequestParam(name = "id", defaultValue = "1")
extracts the query parameterid
from the URL. If not provided, it defaults to1
.@RequestParam(name = "name", required = false)
extracts the optional query parametername
from the URL.
Example
2. Using `@PathVariable`
Example: Handling Path Variables
UserController.java
```java
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;
}
}
```
Example URL: `/user/123`
In this example:
@PathVariable Long id
extracts the value ofid
from the URL path.
Summary of Differences RequestParam and PathVariable
@RequestParam
:- Purpose: Extracts parameters from the query string or form data.
- Usage: Common for optional or default parameters.
- Example:
/user?id=123&name=JohnDoe
@PathVariable
:- Purpose: Extracts values from URI template variables in the path.
- Usage: Common for identifying resources in RESTful services.
- Example:
/user/123