问题
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.
回答1:
@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.
回答2:
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.
回答3:
@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.
来源:https://stackoverflow.com/questions/37878684/when-to-choose-requestparam-over-pathvariable-and-vice-versa