Search code examples
javarestjakarta-eejax-rsjava-ee-7

Multiple GET methods match: select most specific


I have a web service that looks like:

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

The idea is that I can either call:

  • http://ws:8080/ws?id=1 to get a specific record
  • http://ws:8080/ws to get all available records

However when I use the second URL, the first @GET method is called with a null id.

Is there a way to achieve what I want without using different paths?

I think this can be achieved with Spring using the @RequestMapping(params={"id"}) and @RequestMapping annotations for the first and second methods respectively but I can't use Spring in that project.


Solution

  • Since the path is the same, you cannot map it to a different method. If you change the path using REST style mapping

    @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(); } 
    

    then you should use:

    • http://ws:8080/ws/1 to get a specific record
    • http://ws:8080/ws to get all available records