RESTEasy 系列 Chapter 5 @PathParam

@PathParam是一个参数注解,允许你映射URI路径片断变量到你的方法调用。

 

 

@Path("/library")
public class Library {

   @GET
   @Path("/book/{isbn}")
   public String getBook(@PathParam("isbn") String id) {
      // search my database and get a string representation and return it
   }
}

 

这允许你在你的资源当中,在你的URI内嵌入变量识别。在上面的示例,我们需要访问的书本信息通过一个URI参数isbn,你注入的该参数的类型可以是基本类型,一个字符串,或者任何拥有接收一个字符串参数构造方法的Java对象,或一个静态的接收字符串参数的valueOf方法。示例中,比方说我们希望isbn是一个真正的对象,我们可以这样做:

 

   @GET
   @Path("/book/{isbn}")
   public String getBook(@PathParam("isbn") ISBN id) {...}


   public class ISBN {
      public ISBN(String str) {...}
   }
扫描二维码关注公众号,回复: 752469 查看本文章

或者代替公共的String构造方法,拥有一个valueOf方法:

 

 

  public class ISBN {
     
     public static ISBN valueOf(String isbn) {...}
  }

5.1. 高级 @PathParam 和正则表达式

@PathParams有一些更复杂的使用在上一章节中没有讨论。

你可以指定一个或多个路径参数嵌入到一个URI片断,下面是一些示例:

 

1. @Path("/aaa{param}bbb")
2. @Path("/{name}-{zip}")
3. @Path("/foo{name}-{zip}bar")

所以,一个URI "/aaa111bbb" 将匹配 #1. "/bill-02115" 将匹配 #2. "foobill-02115bar" 将匹配#3.

之前我们讨论了你能够如何使用正则表达式到@Path的value:

@GET
@Path("/aaa{param:b+}/{many:.*}/stuff")
public String getIt(@PathParam("param") String bs, @PathParam("many") String many) {...}

  

下面的这些请求,让我们看看"param" 和 "many" 将会是哪些值:

Table 5.1. 

Request

param

many

GET /aaabb/some/stuff

bb

some

GET /aaab/a/lot/of/stuff

b

a/lot/of

 

5.2. @PathParam 和 PathSegment

关于URI路径调用规范有一个非常简单抽象的片断检查,

javax.ws.rs.core.PathSegment:

 

 

public interface PathSegment {

    /**
     * Get the path segment.
     * <p>
     * @return the path segment
     */
    String getPath();
    /**
     * Get a map of the matrix parameters associated with the path segment
     * @return the map of matrix parameters
     */
    MultivaluedMap<String, String> getMatrixParameters();
    
}

 

 

 

 

你要以在resteasy注入一个

PathSegment代替你的

@PathParam的value:

 

 

 

 

 

 

   @GET
   @Path("/book/{id}")
   public String getBook(@PathParam("id") PathSegment id) {...}

 

 

 

 

 

 

这是非常有用的,如果你有一堆的

@PathParam使用矩阵参数。矩阵参数的想法是,它们是嵌入在URI路径片断的任意一对name-value对集合。PathSegment对象允许您访问这些参数,也看到

MatrixParam。

 

 

一个矩阵参数的例子:

 

 

 

 

GET http://host.com/library/book;name=EJB 3.0;author=Bill Burke

矩阵参数的基本思想是,它代表的资源是可寻址的,来自于它们的属性以及它们的原始id。

猜你喜欢

转载自essay.iteye.com/blog/1837554