Using @RequestParam with Default Value
When working with query parameters in Spring Boot there are times when a parameter might not be provided in the URL. In such cases, you can set a default value for the parameter using the `defaultValue` attribute of the `@RequestParam` annotation. This ensures that your application doesn’t break when a parameter is missing.
Let’s say you are building an API to fetch user details. The user might provide a `sortBy` parameter to specify how the results should be sorted. If the user doesn’t provide this parameter, you can default it to `name`. Let’s see how you can do it:
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("/users")
public String getUsers(@RequestParam(defaultValue = "name") String sortBy) {
return "Fetching users sorted by: " + sortBy;
}
}
In this Code:
1. `@RestController`: This annotation marks the class as a controller where every method returns a domain object instead of a view.
2. `@GetMapping("/users")`: This maps HTTP GET requests to the `getUsers` method.
3. `@RequestParam(defaultValue = "name")`: The `defaultValue` attribute ensures that if the `sortBy` parameter is not provided in the URL, it will default to `"name"`.
Example Requests:
- If the URL is `/users`, the output will be:
- Fetching users sorted by: name
- If the URL is `/users?sortBy=age`, the output will be:
- Fetching users sorted by: age
This approach makes your API more robust and user-friendly.
Using @RequestParam For Mapping Multiple Value Query Parameter
Sometimes, you may need to handle multiple values for a single query parameter. For example, a user might want to filter results based on multiple categories or tags. In such cases, you can use `@RequestParam` to map multiple values to a single parameter.
Spring Boot allows you to handle this scenario by binding the query parameter to a `List` or an array. Let’s take an example where a user can filter products by multiple categories.
Let’s see how you can implement it:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class ProductController {
@GetMapping("/products")
public String getProducts(@RequestParam List<String> categories) {
return "Fetching products for categories: " + categories;
}
}
In this Code:
1. `@RequestParam List<String> categories`: This binds all values of the `categories` query parameter to a `List<String>`. If the user provides multiple values for `categories`, they will be stored in this list.
2. `@GetMapping("/products")`: This maps HTTP GET requests to the `getProducts` method.
Example Requests:
- If the URL is `/products?categories=electronics`, the output will be:
- Fetching products for categories: [electronics]
- If the URL is `/products?categories=electronics&categories=books`, the output will be:
- Fetching products for categories: [electronics, books]
This approach is useful when you need to handle multiple values for a single query parameter.
Implementation
Now that we’ve covered the basics of `@RequestParam`, let’s implement a complete Spring Boot application to demonstrate its usage. We’ll create a simple API that handles user requests with query parameters.
Step 1: Set Up a Spring Boot Project
If you don’t already have a Spring Boot project, you can create one using [Spring Initializr](https://start.spring.io/). Include the following dependencies:
Spring Web: For building web applications, including RESTful services.
Once the project is set up, your `pom.xml` (for Maven) or `build.gradle` (for Gradle) should include the Spring Web dependency.
Step 2: Create a Controller
Create a controller class to handle HTTP requests. We’ll use the examples we discussed earlier.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
// Example 1: Using @RequestParam with Default Value
@GetMapping("/users")
public String getUsers(@RequestParam(defaultValue = "name") String sortBy) {
return "Fetching users sorted by: " + sortBy;
}
// Example 2: Using @RequestParam for Multiple Values
@GetMapping("/products")
public String getProducts(@RequestParam List<String> categories) {
return "Fetching products for categories: " + categories;
}
}
Step 3: Run the Application
1. Open the `src/main/java` directory and locate the main application class (e.g., `RequestParamDemoApplication.java`).
2. Run the application by right-clicking the class and selecting `Run`.
Step 4: Test the API
Once the application is running, you can test the API using a browser, Postman, or any HTTP client.
Test Example 1:
- URL: `http://localhost:8080/users`
Output: `Fetching users sorted by: name`
- URL: `http://localhost:8080/users?sortBy=age`
Output: `Fetching users sorted by: age`
Test Example 2:
- URL: `http://localhost:8080/products?categories=electronics`
Output: `Fetching products for categories: [electronics]`
- URL: `http://localhost:8080/products?categories=electronics&categories=books`
Output: `Fetching products for categories: [electronics, books]`
This implementation demonstrates how to use `@RequestParam` in a real-world Spring Boot application.
Dependencies
To use `@RequestParam` in a Spring Boot application, you need to include the necessary dependencies in your project. These dependencies provide the tools and libraries required to build and run a Spring Boot web application.
If you’re using Maven, add the following dependency to your `pom.xml` file:
<dependencies>
<!-- Spring Web: For building web applications, including RESTful services -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot DevTools: Optional, but useful for automatic restarts and live reloads -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
If you’re using Gradle, add the following to your `build.gradle` file:
dependencies {
// Spring Web: For building web applications, including RESTful services
implementation 'org.springframework.boot:spring-boot-starter-web'
// Spring Boot DevTools: Optional, but useful for automatic restarts and live reloads
runtimeOnly 'org.springframework.boot:spring-boot-devtools'
}
Explanation of Dependencies:
1. `spring-boot-starter-web`: This is the core dependency for building web applications with Spring Boot. It includes libraries like Spring MVC, which is essential for handling HTTP requests and using annotations like `@RequestParam`.
2. `spring-boot-devtools`: This is an optional dependency that helps during development. It provides features like automatic application restarts and live reloads, making the development process faster and more efficient.
How to Add Dependencies:
1. Open your project in an IDE like IntelliJ IDEA or Eclipse.
2. Locate the `pom.xml` (for Maven) or `build.gradle` (for Gradle) file in the root directory of your project.
3. Add the dependencies as shown above.
4. Save the file. If you’re using an IDE, it will automatically download the required libraries.
Once the dependencies are added, you’re ready to start building your Spring Boot application with `@RequestParam`.
Context of the Application
Assume we are building a simple API where users can fetch product details using request parameters. The application will demonstrate different use cases of @RequestParam.
Illustration
Let’s create a simple Spring Boot REST controller that demonstrates how @RequestParam works.
Example
@RestController
@RequestMapping("/api")
public class ProductController {
@GetMapping("/product")
public String getProduct(@RequestParam String name) {
return "Product Name: " + name;
}
}
Request:
GET http://localhost:8080/api/product?name=Laptop
Response:
Product Name: Laptop
This example demonstrates basic parameter extraction using @RequestParam.
Simple Mapping Using @RequestParam
When a request contains multiple parameters, we can map them using @RequestParam.
Example
@GetMapping("/user")
public String getUser(@RequestParam String name, @RequestParam int age) {
return "User: " + name + ", Age: " + age;
}
Request:
GET http://localhost:8080/user?name=Alice&age=25
Response:
User: Alice, Age: 25
This example shows how multiple parameters can be passed using @RequestParam.
Specifying the Request Parameter Name Using @RequestParam
Sometimes, the parameter names in the request may differ from the method parameter names. In such cases, we can explicitly specify the request parameter name.
Example:
@GetMapping("/info")
public String getInfo(@RequestParam("user_name") String username) {
return "Username: " + username;
}
Request:
GET http://localhost:8080/info?user_name=Bob
Response:
Username: Bob
Here, the request parameter user_name is mapped to the method argument username.
Handling Optional Parameters with Default Values
If a request parameter is missing, we can provide a default value to avoid errors.
Example
@GetMapping("/greet")
public String greet(@RequestParam(defaultValue = "Guest") String name) {
return "Hello, " + name + "!";
}
Request (without parameter):
GET http://localhost:8080/greet
Response:
Hello, Guest!
This ensures that even if the parameter is missing, the application works smoothly.
Frequently Asked Questions
What is the purpose of @RequestParam in Spring Boot?
@RequestParam is used to extract query parameters from the request URL and bind them to method arguments in a Spring Boot controller.
How can we make a request parameter optional in Spring Boot?
We can use @RequestParam(required = false) to make a parameter optional. We can also provide a default value using defaultValue.
Can @RequestParam handle multiple parameters?
Yes, @RequestParam can handle multiple parameters by defining multiple method arguments in the controller method.
Conclusion
In this article, we learned the @RequestParam annotation in Spring Boot, which is used to extract query parameters from URLs in HTTP requests. It helps in handling user inputs efficiently by making parameters optional, required, or providing default values. Understanding @RequestParam allows developers to manage request data effectively, improving the flexibility and functionality of web applications.