Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to choose @RequestParam over @PathVariable and vice-versa?

I know what @RequestParam does and what @PathVariable does on an individual note but my question is when building a URL, when should I go for @RequestParam and when for @PathVariable? What are the pros and and cons of using both these annotations?

I did go through this link When to go for @RequestParam and @PathVariable but did not get a satisfactory answer anywhere.

like image 682
Akash Raveendran Avatar asked Mar 11 '23 23:03

Akash Raveendran


2 Answers

@PathVariable identifies the pattern that is used in the URI for the incoming request.

Query args (@RequestParam) are used on querying/searching resources exclusively. They contain data that affects the query.

Here are some tips for creating good URLs.

like image 179
Mistalis Avatar answered Apr 06 '23 02:04

Mistalis


It makes more sense to use @Pathvariable to give the user an idea of what the page means.
twitter.com/{userid}
@RequestParamscan be used to get info as parameter, like twitter.com?search=%23yolo
@Pathvariable will help the user navigate or directly move to certain views/pages.

like image 39
Gokul1794 Avatar answered Apr 06 '23 02:04

Gokul1794