In this lesson, you will learn how to read URL query string parameters in your Spring MVC web application.
@RequestParam annotation
Let’s assume that we need to create a method that needs to return a list but is limited to a certain number.
To make our method read URL Query String Parameters, we will need to use a special annotation called @RequestParam.
The good thing about this annotation is that it can help us read not only Query String parameters but also form parameters and even files. This is because the Servlet API combines the query parameters and the form data into a single map called “parameters”.
@GetMapping(path="/users") public ModelAndView getUsers(@RequestParam(name="limit") int limit) { ModelAndView modelAndView = new ModelAndView("users"); return modelAndView; }
Optional Request Parameter
If your method reads request parameter, then by default this request parameter becomes required and must be included in the HTTP request. To make the request parameter optional, you will need to explicitly specify it.
@RequestParam(name="limit", required=false)
Now the limit request parameter is optional.
@GetMapping(path="/users") public ModelAndView getUsers(@RequestParam(name="limit", required = false) int limit) { ModelAndView modelAndView = new ModelAndView("users"); return modelAndView; }
Default value
To provide a default value if the request parameter was not included in the request, we can use another attribute.
@RequestParam(name="limit", defaultValue="30")
Because we have provided the default value, the limit request parameter becomes optional automatically. If the HTTP request does contain this request parameter, then our method will use the value that was provided in the HTTP request. If the HTTP request does not contain the limit request parameter, then the value of the method argument will be equal to 30.
@GetMapping(path="/users") public ModelAndView getUsers(@RequestParam(name="limit", defaultValue = "30") int limit) { ModelAndView modelAndView = new ModelAndView("users"); return modelAndView; }
I hope this tutorial was helpful for you. To learn more about building Web applications with Spring Framework, please visit the Spring Web MVC category. You will find many useful tutorials there.
Happy learning!