Friday, April 19, 2024

Differences between @RequestParam and @PathVariable annotations in Spring MVC?

The Spring MVC framework, one of the most popular frameworks for developing a web application in Java world also provides several useful annotations to extract data from the incoming request and mapping the request to the controller, like @RequestMapping, @GetMapping, @RestController, @RequestParam, and @PathVariable. Even though both @RequestParam and @PathVariable are used to extract values from the HTTP request, there is a subtle difference between them, which makes them a useful question from a Spring Framework interview and spring certification point of view. We'll examine the subtle difference between @RequestParam and @PathVaraible in this article.


As the name suggests, @RequestParam is used to get the request parameters from URL, also known as query parameters, while @PathVariable extracts values from URI.

For example, if the incoming HTTP request to retrieve a book on topic "Java" is http://localhost:8080/shop/order/1001/receipts?date=12-05-2017, then you can use the @RequestParam annotation to retrieve the query parameter date and you can use @PathVariable to extract the orderId i.e. "1001" as shown below:

@RequestMapping(value="/order/{orderId}/receipts", method = RequestMethod.GET)
public List listUsersInvoices( @PathVariable("orderId") int order,
 @RequestParam(value = "date", required = false) Date dateOrNull) {
...
}

The required=false denotes that the query parameter can be optional, but the URL must have the same URI.

By the way, if you are new to the Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at Spring Framework 6: Beginner to Guru, one of the comprehensive and hands-on courses to learn modern Spring. It' also the most up-to-date and covers Spring 5.



How to extract Query Parameters in Spring MVC using @RequestParam?

Spring MVC is a rich framework to develop both web applications and RESTful web services in Java. It provides several ways to retrieve data from the incoming HTTP requests like
  • Request Parameters
  • Path Variables
  • Form inputs
Now that you know the difference between @RequestParam and @PathVariable in Spring MVC. Let's see how to write Spring controllers that can handle request parameters and path variables.

1. Using @RequestParam to get Query parameters

In a Spring MVC application, you can use the @RequestParam annotation to accept query parameters in Controller's handler methods.

For examples, suppose you have a web application that returns details of orders and trades, and you have the following URLs:

http://localhost:8080/eportal/orders?id=1001

To accept the query parameters in the above URLs, you can use the following code in the Spring MVC controller:
@RequestMapping("/orders")
public String showOrderDetails(@RequestParam("id") String orderId, Model model){
   model.addAttribute("orderId", orderId);
   return "orderDetails";
}


If the name of the query parameter is the same as the name of the variable in the handler's @RequestParam annotated argument then you can simply use @RequestParam without specifying the name of a query parameter, Spring will automatically derive the value (see Spring Framework: Spring MVC Fundamentals).

Differences between @RequestParam and @PathVariable annotations in Spring MVC?



Also, here is the code to prove the point:

URL: http://localhost:8080/eportal/trades?tradeId=2001
@RequestMapping("/trades")
public String showTradeDetails(@RequestParam String tradeId,
                               Model model){
  model.addAttribute("tradeId", tradeId);
  return "tradeDetails";
}

You can see that we have just annotated the method parameter tradeId with @RequestParam without specifying the name of the query parameter because the name of both request parameter and argument name is the same, i.e., "tradeId."

If you are interested in learning more about the @RequestParam annotations and other useful Spring MVC annotations, I suggest you check out Spring Framework 6: Beginner to Guru, one of the valuable resources for learning Spring MVC 5.

Differences between @RequestParam and @PathVariable in Spring MVC?




2. Using @PathVariable annotation to extract values from URI

You can use Spring MVC's @PathVaraible annotation to extract any value which is embedded in the URL itself. Spring calls it a URI template, where @PathVariable is used to obtain some placeholders from the URI itself.

If you have worked in RESTful Web services, you might know that the REST URIs contains values, like a REST API to retrieve a book using an ISBN number looks like the following:

URL: http://localhost:8080/book/9783827319333

Now, to extract the value of ISBN number from the URI in your Spring MVC Controller's handler method, you can use @PathVariable annotation as shown in the following code:
@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)
public String showBookDetails(@PathVariable("ISBN") String id,
                              Model model){
   model.addAttribute("ISBN", id);
   return "bookDetails";
}

Similar to @RequestParameter annotation, you also can also omit the value attribute in @PathVariable annotation, if the name of the path variable's placeholder in the @RequestMapping annotation is the same as the variable name in the handler method's @PathVariable annotated parameter (see REST with Spring course by Eugen Paraschive to learn more).

For example, you can rewrite the above code as shown below:
@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)
public String showBookDetails(@PathVariable String ISBN, 
                              Model model){
   model.addAttribute("ISBN", ISBN);
   return "bookDetails";
}


Spring MVC provides several useful annotations to map and extract data from the HTTP request, and as of Spring developer, you should be aware of these, like @RequestMapping, @RequestParam, and @PathVariable.

These concepts and annotations are fundamental from both Spring MVC interview prospects as well as Spring certifications. You will always find a couple of questions based on these concepts.

Btw, if you are preparing for Spring Professional Certifications, you can also check out David Mayer's free Spring Mock Questions to get an idea about the level of questions and format of questions you can expect on real Spring Web Certification.

@RequestParam vs @PathVariable annotations in Spring MVC?



Difference between @PathVariable and @RequestParam in Spring

Now that we understand both the difference as well as how to use both @RequestParam and @PathVariable in the Spring MVC application, let's revise the critical difference between them from an interview perspective.

1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.

2) @RequestParam is more useful on a traditional web application where data is mostly passed in the query abatements while @PathVariable is more suitable for RESTful web services where URL contains values, like http://localhost:8080/book/9783827319333, here data, which is ISBN number is part of URI.

If you want to learn more about how to effectively develop REST applications using Spring, I suggest you join Eugen Paraschiv's REST with Spring course. It's an online course that will teach you the nitty-gritty of developing both REST API and services for real-world scenarios.

Eugen has extensive experience in developing RESTful web services using Spring, and this course is a great way to tap into his knowledge.

3) @RequestParam annotation can specify default values if a query parameter is not present or empty by using a defaultValue attribute, provided the required attribute is false.

4) Spring MVC allows you to use multiple @PathVariable annotations in the same method, provided, no more than one argument has the same pattern.


That's all about the difference between @PathVariable and @RequestParam in Spring MVC. Even though both are used to extract data from URL, @RequestParam is used to retrieve query parameters, anything after? in the URL, while @PathVariable is used to retrieve values from URI itself.

This concept is essential for both traditional web application development as well as developing RESTful Web Services using Spring, so you must spend some time to understand it better.


Other Spring MVC articles you may like to explore

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions, please drop me a note. 

P. S. - If you are new to Spring and Spring Boot and looking for a free Spring Boot online course then I also recommend you to join the Spring Boot 3 Restful Web Services Tutorial - Free Course course by Dan Vega on Udemy. It's one of the best free courses to learn Spring Boot for Java developers. 

8 comments :

Unni Vemanchery Mana said...

Please change @ParthVariable to @PathVariable in the beginning of the article.
Thank you

javin paul said...

done, thanks for pointing it out.

Dragos said...

Please change the @RequestParameter to @RequestParam in the paragraph "Using @PathVariable annotation to extract values from URI". Thank you!

javin paul said...

Hello @Dragos, thanks for pointing out, will correct.

Anonymous said...

URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(
"/{id}").buildAndExpand(course.getId()).toUri();



Can anyone please explain me above code. As I am a beginner, it will be helpful to me very much.

javin paul said...

Hello @Anonymous, this code is dynamically building a URI, It is replacing variable Id in path with course.getId() and then returning a proper URI.

Anonymous said...

Can you provide more questions on spring boot with microservices.

javin paul said...

Hello Anonymous, I have shared 20 Spring Boot Questions and 15 Microservices Interview Questions here, you can check them too.

Post a Comment