2010-09-02 48 views
9

是否可以配置GET方法來讀取可變數量的URI參數並將它們解釋爲可變參數(數組)或集合?我知道查詢參數可以讀取爲列表/設置,但我不能爲他們去我的情況。是否可以使用可變數量的URI參數配置JAX-RS方法?

例如爲:

@GET 
@Produces("text/xml") 
@Path("list/{taskId}") 
public String getTaskCheckLists(@PathParam("taskId") int... taskId) { 
    return Arrays.toString(taskId); 
} 

在此先感謝

回答

8

如果我正確理解你的問題,@Path註釋可以採取正則表達式來指定路徑組件列表。例如,如下所示:

@GET 
@Path("/list/{taskid:.+}") 
public String getTaskCheckLists(@PathParam("taskid") List<PathSegment> taskIdList) { 
    ...... 
} 

還有一個更廣泛的示例here

+0

謝謝,這可能是最接近我會到達那個所以現在我只需要放在那裏正則表達式匹配數字和斜槓example.com/ws/list/1或example.com/ws/list/1/2/3/4/5/6 – zeratul021 2010-09-10 12:47:50

2

我不會將此作爲答案提交,因爲它僅僅是currently accepted answer上的一個邊緣案例,這也是我用過的。 在我的情況下(Jersey 1.19)/list/{taskid:.+}不適用於零變量參數的邊緣情況。將RegEx更改爲/list/{taskid:.*}已妥善處理。另見this article(這似乎是適用的)。

此外,在改變正則表達式的基數爲指標來*(而不是+)我也只好空字符串的情況下,程序處理,我將在List<PathSegment>轉化爲List<String>(把它傳遞到我的數據庫的訪問碼)。

我翻譯從PathSegmentString的原因是我不希望javax.ws.rs.core包中的類污染我的數據訪問層代碼。

這裏有一個完整的例子:

@Path("/listDirs/{dirs:.*}") 
@GET 
@Produces(MediaType.APPLICATION_JSON) 
public Response listDirs(@PathParam("dirs") List<PathSegment> pathSegments) { 
    List<String> dirs = new ArrayList<>(); 
    for (PathSegment pathSegment: pathSegments) { 
     String path = pathSegment.getPath(); 
     if ((path!=null) && (!path.trim().equals(""))) 
      dirs.add(pathSegment.getPath()); 
    } 
    List<String> valueFromDB = db.doSomeQuery(dirs); 
    // construct JSON response object ... 
} 
相關問題