【发布时间】:2011-04-07 10:38:20
【问题描述】:
我是 RESTful 球衣的新手。请问@PathParam和@QueryParam穿球衣有什么区别?
【问题讨论】:
我是 RESTful 球衣的新手。请问@PathParam和@QueryParam穿球衣有什么区别?
【问题讨论】:
查询参数添加到? 标记之后的url,而路径参数是常规URL 的一部分。
在tom下面的URL中可能是路径参数的值,并且有一个名为id和值1的查询参数:
http://mydomain.com/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 : users/query?from=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) {
...
}
}
【讨论】: