I understand what the @PathVariable, @RequestParam and @RequestBody does in Spring, but not clear on which scenarios we have to use them as they are used for extracting value from the URI. Why we have to send data like localhost:8080/getBooks/time and localhost:8080/getBooks?book=time.
Example 1:
@RequestParam is used mainly for filtering purposes
Lets say you want to get George Martin's book:
GET localhost:8080/books?author=georgemartin
Here we pass author=georgemartin as request parameter. This will supposedly get all of Martin's books, example game of thrones series.
This will be used mainly for GET operation.
Example 2:
@PathVariable is used mainly for getting individual objects or piece of data
Lets say you want to get a book by its id:
GET localhost:8080/books/1
Here we pass 1 as path variable. This will supposedly get the 1 book with id 1, example first part of game of thrones' book.
This will be used mainly for DELETE/GET operation.
Example 3:
@RequestBody is used mainly for saving object(s)(or piece of data)
Lets say you want to add a book:
POST localhost:8080/books/
With request body having following attributes:
{
"author":"George Martin",
"Book":"Game of thrones"
...
...
}
This will add a book to the db. This would be used mainly for PUT/POST operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With