How do you handle query parameters in Spring MVC?
Table of Contents
- Introduction
- 1. Basic Query Parameter Handling with
**@RequestParam**
- Explanation:
- 2. Handling Optional Query Parameters
- Explanation:
- 3. Multiple Query Parameters
- Explanation:
- 4. Binding Multiple Values to a Single Parameter
- Explanation:
- 5. Customizing the Parameter Binding
- Explanation:
- Explanation:
- 6. Handling Complex Query Parameters with a Custom Object
- Explanation:
- 1. Basic Query Parameter Handling with
- 7. Conclusion
Introduction
In Spring MVC, query parameters are a common way for clients to send additional information in the URL. For example, a query parameter can be used to filter results, specify search criteria, or control pagination. Spring MVC makes it easy to access these parameters through the @RequestParam
annotation, which allows you to capture parameters from the URL and bind them to method parameters in your controller.
In this guide, we will walk you through how to handle query parameters in Spring MVC, explaining how to retrieve, validate, and use query parameters effectively in your web applications.
1. Basic Query Parameter Handling with **@RequestParam**
The most common way to access query parameters in Spring MVC is by using the @RequestParam
annotation. This annotation binds the value of the query parameter in the request URL to a method parameter in your controller.
Example: Basic Query Parameter Handling
Consider the following example where a controller accepts a search query as a query parameter.
URL Example:
http://localhost:8080/search?query=laptop
Explanation:
**@RequestParam**
: Binds thequery
parameter from the URL to the method parameterquery
.- When a client requests
/search?query=laptop
, the response will be"Searching for: laptop"
.
2. Handling Optional Query Parameters
Sometimes, query parameters are optional, meaning they may or may not be included in the request. In such cases, Spring provides an option to make the parameter optional by specifying a default value or using Optional<T>
from Java 8.
Example: Optional Query Parameters
URL Examples:
http://localhost:8080/search?query=laptop
→"Searching for: laptop"
http://localhost:8080/search
→"Searching for: all"
Explanation:
**required = false**
: Makes thequery
parameter optional.**defaultValue = "all"**
: Specifies the default value to be used when thequery
parameter is not provided in the request.
Alternatively, you can use Optional<T>
for more flexibility:
URL Examples:
http://localhost:8080/search?query=laptop
→"Searching for: laptop"
http://localhost:8080/search
→"Searching for: all"
3. Multiple Query Parameters
You can also handle multiple query parameters in a single method by specifying multiple @RequestParam
annotations for each parameter.
Example: Multiple Query Parameters
URL Example:
http://localhost:8080/products?category=electronics&limit=5&sort=price
Explanation:
- The method takes three parameters:
category
,limit
, andsort
. **category**
is required.**limit**
is optional with a default value of10
.**sort**
is optional and can benull
if not provided.
4. Binding Multiple Values to a Single Parameter
Spring MVC allows you to bind multiple values of a query parameter to a collection type, such as a List
or Set
. This is useful when you expect a parameter to have multiple values in the query string.
Example: Handling Multiple Values for a Query Parameter
URL Example:
http://localhost:8080/categories?categories=electronics&categories=clothing&categories=home
Explanation:
**List<String> categories**
: Spring binds the multiple values of thecategories
query parameter to aList
of strings.- The response will be
"Categories: electronics, clothing, home"
.
5. Customizing the Parameter Binding
Spring provides various ways to customize how query parameters are bound to method parameters, including conversion and validation.
Example: Custom Type Conversion
URL Example:
http://localhost:8080/products?minPrice=100&maxPrice=500
Explanation:
- Spring automatically converts the query parameters
minPrice
andmaxPrice
from string toDouble
before passing them to the method.
Example: Custom Validator for Query Parameters
You can use Spring’s built-in validation annotations to validate query parameters.
URL Example:
http://localhost:8080/products?page=1
Explanation:
**@Min(1)**
: Ensures that thepage
parameter is at least 1. If not, Spring will throw aConstraintViolationException
.
6. Handling Complex Query Parameters with a Custom Object
Sometimes, it makes sense to encapsulate multiple query parameters into a custom object. You can use @ModelAttribute
to bind multiple query parameters to a single Java object.
Example: Binding Multiple Parameters to a Custom Object
URL Example:
http://localhost:8080/products?category=electronics&brand=Samsung&minPrice=100
Explanation:
**@ModelAttribute**
: Binds query parameters to the fields of theProductSearchCriteria
object.- Spring automatically maps the query parameters (
category
,brand
,minPrice
) to the fields of the object.
7. Conclusion
Handling query parameters in Spring MVC is straightforward and flexible. The @RequestParam
annotation provides an easy way to access and bind query parameters to controller method parameters. You can handle optional parameters, validate them, bind multiple values to collections, and even use custom objects to encapsulate complex query data. With Spring’s powerful parameter binding features, you can efficiently manage query parameters and ensure that your application handles client requests in a clean and scalable manner.
Key points to remember:
- Use
@RequestParam
to bind query parameters to method parameters. - Make query parameters optional with
required=false
orOptional<T>
. - Handle multiple values for a parameter with
List
orSet
. - Use custom objects and
@ModelAttribute
for complex query parameter mappings. - Validate query parameters using Spring’s built-in annotations.