英文:
@PathVariable vs @RequestParam to retrieve an entity
问题
我知道 @PathVariable
和 @RequestParam
之间的区别,但这不是重点。
我也阅读了一些文章,但在简单的情况下我仍然不明白何时使用其中之一。
对于一个 REST API,假设我有一个带有 id
和 username
(都是唯一的)的 User
实体。
现在我想通过用户名获取一个用户。
我有两个选项:
@GetMapping(path = "/users/{username}")
public ResponseEntity<Object> getUser(@PathVariable String username){
//获取用户
}
或者
@GetMapping(path = "/users")
public ResponseEntity<Object> getUser(@RequestParam String username){
//获取用户
}
我应该使用哪个选项(代码中的 @RequestParam 不是必需的,我只是为了更清楚地放置它)?
谢谢
英文:
I know the difference between @PathVariable
and @RequestParam
, that's not the point.
I have also read some articles but I still don't understand when to use one or the other in a simple case.
For a REST API, let's say I have a User
entity with id
and username
(both are unique).
Now I want to get a user by username.
I have 2 options :
@GetMapping(path = "/users/{username}")
public ResponseEntity<Object> getUser(@PathVariable String username){
//Get user
}
or
@GetMapping(path = "/users}")
public ResponseEntity<Object> getUser(@RequestParam String username){
//Get user
}
Which one do I have to use (@RequestParam is not mandatory in the code, I placed it just to be clearer) ?
Thanks
答案1
得分: 3
URL的路径部分标识着一个资源,而查询字符串代表一个查询。虽然一个查询可以确切地返回一个项目,但一个集合资源的URL(/users
)应该返回一个项目的_数组_(从零到无穷多),而一个记录资源的URL(/users/123
)应该返回_确切的一个项目_(这是应该处理DELETE/PUT请求的URL)。
如果username
实际上是用户的规范ID,那么它应该是一个路径变量;如果有不同的规范ID(比如UUID),但你通过用户名进行搜索,那么使用一个查询参数,但返回零个或一个结果的集合(你可以在请求映射中使用params=username
,只有当该查询参数存在时才匹配控制器)。
英文:
The path part of a URL identifies a resource, and a query string represents a query. While a query can certainly return exactly one item, a collection-resource URL (/users
) should return an array of items (from zero to infinity), while a record-resource URL (/users/123
) should return exactly one item (and this is the URL that should handle DELETE/PUT requests).
If the username
is actually the canonical ID for the user, it should be a path variable; if there is a different canonical ID (such as a UUID), but you're searching by username, then use a query parameter but return a collection of zero or one results. (You can use params=username
in the request mapping to only match the controller when that query parameter is present.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论