【问题标题】:What is the difference between @PathParam and @QueryParam@PathParam 和 @QueryParam 有什么区别
【发布时间】:2011-04-07 10:38:20
【问题描述】:

我是 RESTful 球衣的新手。请问@PathParam@QueryParam穿球衣有什么区别?

【问题讨论】:

    标签: rest jersey jax-rs


    【解决方案1】:

    查询参数添加到? 标记之后的url,而路径参数是常规URL 的一部分。

    tom下面的URL中可能是路径参数的值,并且有一个名为id和值1的查询参数:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        另外,查询参数可以为空,但路径参数不能。如果你不附加路径参数,你会得到 404 错误。因此,如果您想强制发送数据,可以使用路径参数。

        【讨论】:

          【解决方案4】:
              @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) {
                  ...
                  }
                  }
          

          【讨论】:

            猜你喜欢
            • 2012-05-12
            • 2015-11-28
            • 2014-12-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多