![](/img/trans.png)
[英]Java RESTful services - What is the difference between QueryParam and PathParam in terms of their usage?
[英]What is the difference between @PathParam and @QueryParam
我是 RESTful 球衣的新手。 我想问一下@PathParam
和@QueryParam
在球衣上的区别是什么?
查询参数被添加到 URL 之后?
标记,而路径参数是常规 URL 的一部分。
在下面的 URL 中, tom
可能是路径参数的值,并且有一个名为id
和值为1
的查询参数:
http://mydomain.example/tom?id=1
除了@Ruben 提供的上述说明外,我想补充一点,您还可以在 Spring RESTFull 实现中引用相同的内容。
JAX-RS 规范 @PathParam - 将 URI 模板参数或包含模板参数的路径段的值绑定到资源方法参数、资源类字段或资源类 bean 属性。
@Path("/users/{username}")
public class UserResource {
@GET
@Produces("text/xml")
public String getUser(@PathParam("username") String userName) {
...
}
}
@QueryParam - 将 HTTP 查询参数的值绑定到资源方法参数、资源类字段或资源类 bean 属性。
URI:用户/查询?从=100
@Path("/users")
public class UserService {
@GET
@Path("/query")
public Response getUsers(
@QueryParam("from") int from){
}}
要使用 Spring 实现相同的功能,您可以使用
@PathVariable(Spring) == @PathParam(Jersey, JAX-RS),
@RequestParam(Spring) == @QueryParam(Jersey, JAX-RS)
此外,查询参数可以为空,但路径参数不能。 如果你不附加路径参数,你会得到 404 错误。 因此,如果您想强制发送数据,则可以使用路径参数。
@javax.ws.rs.QueryParam
This annotation allows you to extract values from URI query parameters.
@javax.ws.rs.PathParam
This annotation allows you to extract values from URI template parameters.
PART-1 : @javax.ws.rs.PathParam
@Path("/mercedes")
public class MercedesService {
@GET
@Path("/e55/{year}")
@Produces("image/jpeg")
public Jpeg getE55Picture(@PathParam("year") String year) {
...
}
If I query the JAX-RS service with GET /mercedes/e55/2006, the getE55Picture()
method would match the incoming request and would be invoked.
PART-2 : @javax.ws.rs.QueryParam
URI might look like this: GET /cus?start=0&size=10
@Path("/cus")
public class GreedCorruption {
@GET
@Produces("application/xml")
public String getDeathReport(@QueryParam("start") int start,
@QueryParam("size") int size) {
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.