5

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.

Community
  • 1
  • 1
Akash Raveendran
  • 559
  • 1
  • 9
  • 22
  • Possible duplicate of [@RequestParam vs @PathVariable](http://stackoverflow.com/questions/13715811/requestparam-vs-pathvariable) – mnwsmit Jun 17 '16 at 10:08
  • @mnwsmit No, not duplicate. There it tells what both these annotations are but doesnt weigh each against the other. I want a comparison plus I want to know the scenarios where each of them are better to use. – Akash Raveendran Jun 17 '16 at 10:10
  • In that case the question is probably too broad for stackoverflow – mnwsmit Jun 17 '16 at 10:11

3 Answers3

4

@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.

Mistalis
  • 17,793
  • 13
  • 73
  • 97
3

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.

Gokul1794
  • 137
  • 11
0

@PathVariable:

When u need to pass parameters along with the url to get the data. In Spring MVC, u can customize the URL in order to get data. For this purpose @PathVariable annotation is used in Spring framework. @PathVariable is used to obtain some placeholder from the uri (Spring call it an URI Template).

@RequestParam:

Is used to obtain an request parameter. @RequestParam binds a request parameter to a parameter in your method.

FuSsA
  • 4,223
  • 7
  • 39
  • 60