SPRING BOOT @RequestParam
SPRING BOOT
The @RequestParam annotation is used to extract query parameters and form data from the URL path of an HTTP request and attach them to the method parameters of a REST controller.
Spring Boot @RequestParam Annotation
➔ The @RequestParam annotation is used to extract form data and query parameters from the URL path of an HTTP request to the server and bind those values to a method parameter in the controller.
Key characteristics of the @RequestParam annotation:
➔ The @RequestParam annotation is used to extract query parameters and values from the URL path and attach them to the controller's method parameters.
➔ @RequestParam is mainly used to map values from URL query strings to Java variables in method parameters and can be used multiple times in a method if needed.
➔ @RequestParam also binds the form data sent in the request body to Content-Type:application/x-www-form-urlencoded and maps it to a DTO or domain model.
Basic Usage Syntax
URL: https://localhost:8090/api/customers?customerid=100
@PostMapping(value="/api/customers")
public String customerHandler(@RequestParam(value="customerid") int cid) {
return "Customer ID: "+cid;
}
➔ A single handler method can handle multiple request parameters.
URL: https://localhost:8090/api/customers?customerid=100&orderid=500
@PostMapping(value="/api/customers")
public String customerHandler(@RequestParam(value="customerid") int cid, @RequestParam(name="orderid") int oid) {
return "Customer ID: "+cid +"\nOrder ID: "+oid;
}
➔ Spring boot automatically converts String input values to the target method parameter type (such as String, int, long, Boolean, etc.).
➔ If the name of the Java method variable and the name of the URL parameter are different, the explicit name must be declared in the annotation.
➔ If the name of the Java method variable and the name of the URL parameter are the same, declaring the name explicitly in the annotation is optional.
URL: https://localhost:8090/api/customers?customerid=100&orderid=500
@PostMapping(value="/api/customers")
public String customerHandler(@RequestParam int customerid, @RequestParam int orderid) {
return "Customer ID: "+customerid +"\nOrder ID: "orderid;
}
Making Request Parameters Optional in URL:
➔ By default the parameters are mandatory and a 400 Bad Request error occurs if they are not provided with the request.
➔ @RequestParam is required and these values can be made optional by setting required=false.
➔ Using `required=false` prevents Spring Boot from throwing an exception even if the parameter is missing.
URL: https://localhost:8090/api/customers
@PostMapping(value = "/api/customers")
public String customerHandler(@RequestParam(required = false) Integer customerid,
@RequestParam(value = "orderid", required = false) String oid) {
return "Customer ID: " + customerid + "\nOrder ID: " + oid;
}
//Output
Customer ID: null
Order ID: null
Setting default values for Request Parameters:
➔ The @RequestParam annotation has a built-in defaultValue attribute, so the default value can be set using this attribute, for example: @RequestParam(defaultValue = "500").
➔ If the parameter is missing from the request URL, the defaultValue attribute provides a fallback value for the parameter, to avoid null values or exceptions.
➔ Setting defaultValue automatically makes required false, so the required attribute is optional when using the defaultValue attribute.
➔ The name/value attributes in @RequestParam are aliases of each other.
URL: https://localhost:8090/api/customers
@PostMapping(value = "/api/customers")
public String customerHandler(@RequestParam(name="customerid", defaultValue = "101") int cid,
@RequestParam(value = "orderid", defaultValue = "501") String oid) {
return "Customer ID: " + cid + "\nOrder ID: " + oid;
}
//Output
Customer ID: 101
Order ID: 501
Collecting multiple parameters with the same name.
URL: localhost:8090/api/customers?customerid=100&customerid=102&customerid=105
@PostMapping(value = "/api/customers")
public String customerHandler(@RequestParam(name="customerid") List<String> ids) {
return "Search for : " + ids;
}
//Output
Search for : [100, 102, 105]
Collecting multiple parameters under different names.
URL: localhost:8090/api/customers?customerid=100&orderid=500&name=maria
@PostMapping(value = "/api/customers")
public String customerHandler(@RequestParam Map<String, String> allParams) {
return "Parameters map : " + allParams +"\nEntryset: "+allParams.entrySet()+
"\nKeyset: "+allParams.keySet()+"\nvalues: "+allParams.values();
}
//Output
Parameters map : {customerid=100, orderid=500, name=maria}
Entryset: [customerid=100, orderid=500, name=maria]
Keyset: [customerid, orderid, name]
values: [100, 500, maria]
Difference between @RequestParam and @PathVariable
| Features | @RequestParam | @PathVariable |
|---|---|---|
| Data extraction source | From Query string such as (/customers?id=1) | From URL Path such as (/customers/id/1) |
| Purpose of data extraction | Filtering, sorting, searching. | Identifying and accessing specific resources. |
| Flexibility | This approach is best suited for extracting optional parameters. | This approach is best suited for creating RESTful APIs for client applications. |
Now practice this chapter in your learning environment.
01 Create a Spring Boot project using Spring Tool Suite (STS).
02 Create a Controller class
Name it anything, for example UsersController.
Controller Code
package com.exam.helloworld;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UsersController {
@PostMapping(value = "/api/customers")
public String customerHandler(@RequestParam(name = "customerid", defaultValue = "101") int cid,
@RequestParam(value = "orderid", defaultValue = "501") String oid) {
return "Customer ID: " + cid + "\nOrder ID: " + oid;
}
}
03 Run HelloworldApplication.java
After successfully run the application.
Now test the @RequestParam in Postman (an API testing tool).
@RequestParam defaultValue attribute sets the default fallback value for the parameter (with parameters).
@RequestParam without parameter values in request URL (without parameters).