@PathParam和@QueryParam有什么区别

时间:2011-04-07 10:38:20

标签: rest jersey jax-rs

我是RESTful球衣的新手。我想问一下球衣中@PathParam@QueryParam之间有什么不同?

4 个答案:

答案 0 :(得分:131)

查询参数会添加到?标记后的网址中,而路径参数则是常规网址的一部分。

在下面的网址中,tom可以是路径参数的值,并且有一个名称为id且值为1的查询参数:

http://mydomain.com/tom?id=1

答案 1 :(得分:11)

除了@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)

答案 2 :(得分:0)

此外,查询参数可以为null,但path参数不能为null。如果不附加path参数,则会出现404错误。因此,如果要强制发送数据,则可以使用path参数。

答案 3 :(得分:0)

    @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) {
        ...
        }
        }
相关问题