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

若如初见. 提交于 2020-08-05 05:55:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!