Bind request parameter with method argument using @RequestParam annotation in Spring MVC

Using the @RequestParam annotation along with the @RequestMapping annotation we can bind the parameter request with the method argument in Spring MVC. How is it in details? We will find out in this tutorial.

Assuming now, we need to build a Controller to handle the request from the client like: /login?username=Khanh&password=abc.

Normally, to solve this problem, we will create a new Controller with a method as follows:

With the HttpServletRequest object containing all the information from the request, we can easily retrieve the value of two request parameters as username and password.

However, here is another easy way to get information about two request parameters: username and password, which is to use the @RequestParam annotation in Spring MVC.

With @RequestParam annotation, our code is as simple as:

As you can see, we do not need to use the HttpServletRequest object to get the value of the two username and password parameters. Now, the values of these two parameters are automatically binded to the username and password arguments in the login() method. This automatic bind only happens when the arguments name in the method and the name of the request parameter are the same.

If the argument name in the method and the name of the request parameter are not the same then you can use the value attribute of the @RequestParam annotation and declare the name of the request parameter to bind.

For example, now I want to make the name of the username argument shorter, just user, then I will declare the value of the annotation value @RequestParam as follows:

With the @RequestParam annotation, we can specify whether the request parameter is mandatory or optional by declaring the required attribute.

By default, if you do not declare the required attribute, then the value is true.

And the last thing, I want to say, related to the @RequestParam annotation, is: we can specify the default value of a request parameter in case the request parameter is null or empty.

For example, we declare the username parameter as follows:



Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
3Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.