2016-12-12 90 views
0

我正在嘗試向我的REST API添加新功能。Java REST API查詢註釋

基本上我想添加查詢參數添加到路徑末尾的功能,並將其轉換爲所有查詢選項的地圖。

我當前的代碼可以讓我做的事情一樣

localhost:8181/cxf/check/ 
localhost:8181/cxf/check/format 
localhost:8181/cxf/check/a/b 
localhost:8181/cxf/check/format/a/b 

,這將使用所有@PathParam爲字符串變量生成響應。

我想現在要做的就是添加:

localhost:8181/cxf/check/a/b/?x=abc&y=def&z=ghi&... 
localhost:8181/cxf/check/format/a/b/?x=abc&y=def&z=ghi&... 

,然後我會對這產生可隨着pathparam被用來建立響應

x => abc 
y => def 
z => ghi 
... => ... 

我是一個地圖想像這樣[下面]但是@QueryParam似乎只處理一個鍵值而不是它們的Map。

@GET 
@Path("/{format}/{part1}/{part2}/{query}") 
Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2, @QueryParam("query") Map<K,V> query); 

下面是我當前的接口代碼。

@Produces(MediaType.APPLICATION_JSON) 
public interface RestService { 

@GET 
@Path("/") 
Response getCheck(); 

@GET 
@Path("/{format}") 
Response getCheck(@PathParam("format") String format); 

@GET 
@Path("/{part1}/{part2}") 
Response getCheck(@PathParam("part1") String part1,@PathParam("part2") String part2); 

@GET 
@Path("/{format}/{part1}/{part2}") 
Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2); 

} 

回答

1

QueryParam("") myBean允許獲得注入的所有查詢參數。還刪除最後一個{query}部分

@GET 
@Path("/{format}/{part1}/{part2}/") 
Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2, @QueryParam("") MyBean myBean); 

public class MyBean{ 
    public void setX(String x) {...} 
    public void setY(String y) {...} 
} 

你也不能聲明參數並解析URI。此選項可能是有用的,如果你能接受非固定參數

@GET 
@Path("/{format}/{part1}/{part2}/") 
public Response getCheck(@PathParam("format") String format, @PathParam("part1") String part1, @PathParam("part2") String part2, @Context UriInfo uriInfo) { 
    MultivaluedMap<String, String> params = uriInfo.getQueryParameters(); 
    String x= params.getFirst("x"); 
    String y= params.getFirst("y"); 
} 
+0

的@Context是我一直在尋找我喜歡(因爲它建立一個地圖) 但是我是有問題得到這個工作( ) 這是否允許我使用@Path(「/ {format}/{part1}/{part2} /」),否則我不得不將它留空,然後從UriInfo稍後提取路徑? –

+0

您可以一起使用'@ PathParam'和'@Context UriInfo'。我在回答中包含了完整的示例 – pedrofb

+0

謝謝我會盡快測試出來謝謝! –