Binding variables in URI request to method’s parameters using @PathVariable annotation in Spring MVC

Usually, when we want to request specific information from a RESTful Web Service, we usually use requests like “/student/2” or “/product/5”, where 2 and 5 are the values can be changed depending on demand. To construct such requests in Spring MVC, we need to define the variables in the URI request and use the @PathVariable annotation to bind the method parameters to these variables. How is it in details? Let’s find out in this tutorial.

First, I will create a Maven project as an example:

Binding variables in URI request to method's parameters using @PathVariable annotation in Spring MVC

If you do not know how to create, let’s follow the instructions of this tutorial.

The default dependencies, I have changed version as follows:

To run this project, I will use Maven Jetty Plugin:

Now, I will create a new Controller named StudentController with the following content:

Now I need to add a request for users to be able to get student information by ID in the form “student/<student_id>”, I will add as follows:

As you can see, in the request URL, I declared {id} to define an <id> variable, and with the use of the @PathVariable annotation in the method parameter, the variable in the request URL would be bind with this parameter. If you now run the application and request to the URL “http://localhost:8080/student/1” then the result will be:

Binding variables in URI request to method's parameters using @PathVariable annotation in Spring MVC

Notice that the name of the variable in the request URL must be the same as the name of the parameter declared with the @PathVariable annotation. In case, the name of the method’s parameter does not match the variable name of the request URL, then you need to declare the value of the value attribute for the annotation @PathVariable:

Then, if you refresh the URL, the result is still the same.

Add Comment