JBoss Resteasy 2之URL匹配

来源:互联网 发布:淘宝开店保证金怎么退 编辑:程序博客网 时间:2024/06/06 04:55
在上一篇helloworld中,简单介绍了入门,本文讲解其URL匹配,也是REST
中很重要的一环
看例子:

Java代码 复制代码
  1. @Path("/users")   
  2. public class UserRestService {   
  3.     
  4.     @GET  
  5.     @Path("{name}")   
  6.     public Response getUserByName(@PathParam("name") String name) {   
  7.     
  8.         return Response.status(200)   
  9.             .entity("getUserByName is called, name : " + name).build();   
  10.     
  11.     }   
  12.     @GET  
  13.     @Path("{id : \\d+}"//support digit only  
  14.     public Response getUserById(@PathParam("id") String id) {   
  15.     
  16.        return Response.status(200).entity("getUserById is called, id : " + id).build();   
  17.     
  18.     }   
  19.     
  20.     @GET  
  21.     @Path("/username/{username : [a-zA-Z][a-zA-Z_0-9]}")   
  22.     public Response getUserByUserName(@PathParam("username") String username) {   
  23.     
  24.        return Response.status(200)   
  25.         .entity("getUserByUserName is called, username : " + username).build();   
  26.     
  27.     }   
  28.     
  29.     @GET  
  30.     @Path("/books/{isbn : \\d+}")   
  31.     public Response getUserBookByISBN(@PathParam("isbn") String isbn) {   
  32.     
  33.        return Response.status(200)   
  34.         .entity("getUserBookByISBN is called, isbn : " + isbn).build();   
  35.     
  36.     }  
 

可以看到,还支持正则表达式。所以,容易看出:

1) “/users/999”
返回:getUserById is called, id : 999

2) /users/username/aaa”
  不匹配

3) users/books/999”
  返回:getUserBookByISBN is called, isbn : 999

再看例子:
 
Java代码 复制代码
  1. @Path("/users")   
  2. public class UserRestService {   
  3.     
  4.     @GET  
  5.     @Path("{id}")   
  6.     public Response getUserById(@PathParam("id") String id) {   
  7.     
  8.        return Response.status(200).entity("getUserById is called, id : " + id).build();   
  9.     
  10.     }   
  11.    

则“/users/22667788 匹配
  getUserById is called, id : 22667788

多个参数传入的例子:
 
Java代码 复制代码
  1. @Path("/users")   
  2. public class UserRestService {   
  3.     
  4.     @GET  
  5.     @Path("{year}/{month}/{day}")   
  6.     public Response getUserHistory(   
  7.             @PathParam("year"int year,   
  8.             @PathParam("month"int month,    
  9.             @PathParam("day"int day) {   
  10.     
  11.        String date = year + "/" + month + "/" + day;   
  12.     
  13.        return Response.status(200)   
  14.         .entity("getUserHistory is called, year/month/day : " + date)   
  15.         .build();   
  16.     
  17.     }   
  18.    

则:
“/users/2011/06/30”
输出:
   getUserHistory is called, year/month/day : 2011/6/30