@RequestParam Example in Spring MVC

In this Spring MVC tutorial, you will learn how to use the @RequestParam annotation to read the URL Query request parameters in your Spring MVC Web Services application.

Let’s assume we have the following URL to your Web Service endpoint.

http://localhost:8080/api/users?page=1&limit=50

If we break the above URL down into smaller parts then we will see that:

  • HTTP – is the protocol being used,
  • localhost  – is the domain name,
  • 8080 – is the port number,
  • api – is the root path of your web services application,
  • users – is most likely the @Path value of your Root Resource class and,
  • page – is the URL Query parameter which we can read with @RequestParam annotation,
  • limit – is the URL Query parameter which we can also read with @RequestParam annotation.

Let’s have a look at the example of how we can read the above request URL query string parameters with the @RequestParam annotation.

Read Request URL Query Parameters with @RequestParam

Let’s say we have the below @RestController class with a method which reads the two URL Query string request parameters which are mentioned in the URL above.

To read the request parameter from URL Query string use the @RequestParam annotation in the following way:

@RequestParam(value = "page", defaultValue = "0")

Below is an example of @RestController class:

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public List<UserRest> getUsers(@RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "limit", defaultValue = "30") int limit) {
       
          List<UserRest> returnValue = new ArrayList<>();

        List<UserDto> users = userService.getUsers(page, limit);

        for (UserDto userDto : users) {
            UserRest userModel = new UserRest();
            BeanUtils.copyProperties(userDto, userModel);
            returnValue.add(userModel);
        }

        return returnValue;
    }
}

Please notice how the @RequestParam annotation is used in the method signature to read the two URL Query string request parameters and make them available as method arguments. Please also notice the use how the default value is provided in the case when the request parameter is not set.

I hope this short tutorial on how to read request parameters from URL query string in your Spring MVC application was helpful to you.

If you are interested in learning more about Spring MVC framework, please check the below video courses and hopefully one of them will be just what you were looking for.