Spring

Spring @RequestParam Annotation

Introduction:

Spring @RequestParam annotation can be used to extract the query parameters in a handler method. In this quick tutorial, we’ll learn its usage.

@RequestParam Annotation:

Let’s first expose an API which returns a list of users with a given first name and age:

And now, let’s use cURL to quickly test this out:

As we can see, the firstName and age are the query parameters that got correctly mapped to our handler method.

Attributes of @RequestParam:

The @RequestParam annotation supports the usage of several attributes to cater to various common needs:

1. name/value:

In the example we just covered, we’ll notice that the names of the method argument and query parameter were the same (firstName and age).

However, at times, we might feel the need to have different names. For that, we’ll use its name or value attribute:

With this, the uName and uAge parameters will map to the firstName and age method arguments respectively:

2. required:

By default, if we define a request parameter and don’t pass it in the user request, we’ll get an error.

To avoid that, we can set the required to false:

It’ll assign data type defaults to all optional parameters. When we hit below URL:

the firstName will get mapped to a null value.

3. defaultValue:

If we want to set the required to false and also map a default value to the concerned attribute, we’ll have:

Here, if we don’t pass the firstName query parameter, it’ll assume it to be ‘John’.

@RequestParam with Java List:

We can accept a list of query parameters in a Java List:

To use our new users API, we’ll have something as:

Retrieve All Parameters:

To retrieve all passed query parameters from a user request, we’ll accept them as a Java Map:

This comes handy when we want to retrieve all parameters without knowing their names:

Conclusion:

In this tutorial, we learned how to work with @RequestParam annotation in a Spring application.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *