Spring Boot
query parameters
controller
HTTP requests
Java

How do I retrieve query parameters in a Spring Boot controller?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

In a Spring Boot application, retrieving query parameters in a controller is a common task that allows you to capture parameters from the URL and use them within your application logic. This process facilitates the functionality of web applications by tailoring responses based on client queries. Here we explore various methods to fetch these parameters effectively using Spring Boot. We'll cover methods to retrieve query parameters, including explanations and examples, and introduce additional concepts to solidify your understanding.

Query Parameters in Spring Boot

Query parameters are appended to the URL and are used to pass data to the server. Consider a URL of the form:

 
GET /api/products?category=electronics&sort=asc

Here, category and sort are query parameters.

Retrieving Query Parameters

In Spring Boot, you can retrieve query parameters using the @RequestParam annotation in a controller method. This approach provides a straightforward way to capture parameters.

Basic Usage of @RequestParam

To retrieve a query parameter, annotate a method argument with @RequestParam:

java
1import org.springframework.web.bind.annotation.*;
2
3@RestController
4@RequestMapping("/api/products")
5public class ProductController {
6
7    @GetMapping
8    public String getProducts(@RequestParam String category, @RequestParam String sort) {
9        return "Category: " + category + ", Sort: " + sort;
10    }
11}

In this example, category and sort are captured from the URL as query parameters. The method will return a simple response containing these values.

Handling Default Values

Sometimes, query parameters may be optional. You can specify default values using the defaultValue attribute:

java
1@GetMapping
2public String getProducts(
3    @RequestParam String category,
4    @RequestParam(defaultValue = "asc") String sort) {
5    return "Category: " + category + ", Sort: " + sort;
6}

Here, if the sort parameter is absent, it defaults to "asc".

Specifying Parameters as Optional

Spring Boot also allows parameters to be optional by using the required attribute:

java
1@GetMapping
2public String getProducts(
3    @RequestParam String category,
4    @RequestParam(required = false) String sort) {
5    if (sort == null) {
6        sort = "asc"; // Assign default directly in logic if needed.
7    }
8    return "Category: " + category + ", Sort: " + sort;
9}

By setting required = false, the method can handle URLs missing the sort parameter.

Retrieving Multiple Parameters

For more complex scenarios, you may need to work with numerous query parameters or map them to an object. This can be efficiently managed by using a POJO to represent the parameters.

Using a POJO

First, define a class representing the parameters:

java
1public class ProductQuery {
2    private String category;
3    private String sort;
4    
5    // Getters and setters
6
7    public String getCategory() {
8        return category;
9    }
10
11    public void setCategory(String category) {
12        this.category = category;
13    }
14
15    public String getSort() {
16        return sort;
17    }
18
19    public void setSort(String sort) {
20        this.sort = sort;
21    }
22}

Then, use this class in the controller:

java
1@GetMapping
2public String getProducts(ProductQuery productQuery) {
3    String category = productQuery.getCategory();
4    String sort = productQuery.getSort() != null ? productQuery.getSort() : "asc";
5    return "Category: " + category + ", Sort: " + sort;
6}

Table of Key Points

FeatureDescriptionExample Usage
Basic @RequestParam UsageCaptures mandatory query parameters@RequestParam String category
Default ValuesSets default when parameter is absent@RequestParam(defaultValue = "asc")
Optional ParametersSpecifies that a parameter is not required@RequestParam(required = false)
Mapping to a POJOUses an object to manage multiple paramsProductQuery productQuery

Additional Considerations

  • Type Conversion: Spring Boot can automatically convert query parameters to various data types such as int, double, or even custom types, provided a suitable converter is registered.
  • Validation: Combine @RequestParam with validation annotations like @NotNull or @Size to ensure parameter integrity.
  • Exception Handling: Implement global exception handlers to provide meaningful error responses when query parameters fail validation or conversion.

Conclusion

Retrieving query parameters in a Spring Boot controller is both a basic and crucial part of developing web applications. By leveraging @RequestParam, you can easily capture and use data sent by clients, making your APIs more dynamic and flexible. It's essential to understand the different techniques for handling query parameters, including their default values and optional status, to accommodate various use cases. Mapping query parameters to a POJO can also simplify management for complex requests.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.