Spring Boot
Query Parameters
Controller
Java
Web Development

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Spring Boot is a powerful framework that simplifies development with Java. Often, when building web applications, you need to handle incoming HTTP requests and extract query parameters. Query parameters are key-value pairs sent in the URL following a question mark ?. In a Spring Boot application, you can easily retrieve these parameters in your controller classes using the @RequestParam annotation. This article will delve into the ways you can retrieve query parameters, offering code examples and technical explanations where necessary.

Retrieving Query Parameters in Spring Boot

The primary way to retrieve query parameters in Spring Boot is by using the @RequestParam annotation on method parameters within a controller. This annotation binds a request parameter to a method parameter within the handler method.

Using @RequestParam

When a client sends a request to a Spring Boot application with query parameters, each parameter can be captured and utilized by the application logic. Here's a simple example illustrating how to use @RequestParam in your controller:

java
1import org.springframework.web.bind.annotation.GetMapping;
2import org.springframework.web.bind.annotation.RequestParam;
3import org.springframework.web.bind.annotation.RestController;
4
5@RestController
6public class ExampleController {
7
8    @GetMapping("/greet")
9    public String greetUser(@RequestParam(name = "name", required = false, defaultValue = "World") String name) {
10        return "Hello, " + name;
11    }
12}

In this example:

  • The @GetMapping annotation maps HTTP GET requests onto the greetUser method.
  • The @RequestParam annotation is used to bind the name query parameter to the Java method parameter name.
  • The required attribute is set to false, making it an optional parameter. If not provided, the defaultValue of "World" is used, ensuring the application remains robust against missing parameters.

Handling Multiple Query Parameters

If you have multiple query parameters, you can add additional method parameters, each annotated with @RequestParam.

java
1import org.springframework.web.bind.annotation.GetMapping;
2import org.springframework.web.bind.annotation.RequestParam;
3import org.springframework.web.bind.annotation.RestController;
4
5@RestController
6public class MultiParamController {
7
8    @GetMapping("/user")
9    public String getUserDetails(@RequestParam String id, @RequestParam("age") int userAge) {
10        return "User ID: " + id + " Age: " + userAge;
11    }
12}

Handling Complex Parameters with Maps

For handling a dynamic set of parameters or when dealing with a large number of query parameters, using a @RequestParam of type Map<String, String> can be beneficial:

java
1import org.springframework.web.bind.annotation.GetMapping;
2import org.springframework.web.bind.annotation.RequestParam;
3import org.springframework.web.bind.annotation.RestController;
4
5import java.util.Map;
6
7@RestController
8public class MapParamController {
9
10    @GetMapping("/search")
11    public String processSearch(@RequestParam Map<String, String> queryParameters) {
12        return "Received parameters: " + queryParameters.toString();
13    }
14}

In this example, all query parameters are captured into a map and can be processed programmatically.

Default Values and Required Parameters

  • Default Values: By specifying the defaultValue attribute in @RequestParam, you can ensure that a default is used when the parameter is not provided, which is essential for optional parameters.
  • Required Parameters: By default, @RequestParam assumes all parameters are required. If a required parameter is missing, Spring will throw a MissingServletRequestParameterException. To make a parameter optional, set required=false.

Table Summarizing Key Points

FeatureUsage ExampleDescription
Basic @RequestParam@RequestParam String paramBinds query parameters to method parameters.
Optional Parameters@RequestParam(name = "param", required = false)Sets parameters as optional, avoiding exceptions if missing.
Default Value@RequestParam(defaultValue = "default")Provides a default value if the parameter is not provided.
Multiple Parameters@RequestParam String param1, @RequestParam int param2Handles multiple query parameters in one method.
Dynamic Parameters using Map@RequestParam Map<String, String> paramsCaptures all query parameters into a map.

Conclusion

Retrieving query parameters in a Spring Boot application is both straightforward and flexible, thanks to the @RequestParam annotation. Whether you need to retrieve a single parameter or handle multiple, optional, or default values, Spring Boot provides the necessary tools to manage these requirements effectively. Understanding these methods will enable you to handle web requests with more precision and build powerful web applications with little complexity.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.