2014-11-08 31 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获得所有可用的记录