2014-11-08 33 views
2

我有一個看起來一個Web服務,如:多個GET方法匹配:選擇最具體的

@Path("/ws") 
public class Ws { 
    @GET public Record getOne(@QueryParam("id") Integer id) { return record(id); } 
    @GET public List<Record> getAll() { return allRecords(); } 
} 

的想法是,我可以調用:

  • http://ws:8080/ws?id=1得到一個特定的記錄
  • http://ws:8080/ws獲取所有可用記錄

但是,當我使用第二個URL,第一個@GET方法被稱爲空id

有沒有辦法在不使用不同路徑的情況下實現我想要的功能?

我認爲這是可以分別使用Spring的@RequestMapping(params={"id"})@RequestMapping標註爲第一和第二種方法,但我不能在該項目中使用Spring來實現。

+0

爲什麼不乾脆在你的代碼中實現一個邏輯來檢查param是否爲null,然後返回所有的? – user432 2014-11-08 11:21:07

+0

@ user432這兩種方法沒有相同的返回類型 - 我可以返回一個'Object'我想它看起來有點凌亂...... – assylias 2014-11-08 11:21:40

+1

你回來了什麼?你能否返回一份清單和一份清單? – user432 2014-11-08 11:22:34

回答

2

由於路徑相同,因此無法將其映射到其他方法。如果您在使用REST風格映射

@Path("/ws") 
public class Ws { 
    @GET @Path("/{id}") public Response getOne(@PathParam("id") Integer id) { return Response.status(200).entity(record(id)).build(); } 
    @GET public Response getAll() { return Response.status(200).entity(allRecords()).build(); } 

然後更改路徑,你應該使用:

  • http://ws:8080/ws/1得到一個特定的記錄
  • http://ws:8080/ws獲得所有可用的記錄