2

Currently I am using Jetty + Jersey to make it possible to have different responses according to the @GET parameters, if an id is passed it shall return the task, if not return all tasks.

@GET
@Path("task")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Task> getTask(){
    return tasks;
}

@GET
@Path("task")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Task> getTasks(@QueryParam("id") String id){
    return task(uuid);
}

Is this possible? How can I do it?

Tupac
  • 647
  • 12
  • 37
Gobliins
  • 3,848
  • 16
  • 67
  • 122

2 Answers2

3

I think that a nice soution is something like this:

@GET
@Path("task/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Task getTasks(@PathParam("id") String id) throws JSONException{
    return task(id);
}

But you can do a Class for that resource only and make something like this:

@Path("/tasks")
public class TasksService{

@GET
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Task> getTask() throws JSONException{
    return tasks;
}

@GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Task getTasks(@PathParam("id") String id) throws JSONException{
        return task(id);
    }
}

and you get the resources with localhost:8080/blablabla/tasks => all the tasks localhost:8080/blablabla/tasks/35 => the 35º task

Tupac
  • 647
  • 12
  • 37
  • Can you maybe also tell me what is the difference in having a Response Object as a return value like https://stackoverflow.com/questions/13703807/post-in-restful-web-service ? – Gobliins Aug 27 '15 at 14:23
  • 1
    That is because RESTful typically works with HTTP protocol and they are sending explicitly the HTTP status in the response, so the client can manage that. You can look at this question: [question](http://stackoverflow.com/questions/4687271/jax-rs-how-to-return-json-and-http-status-code-together) – Tupac Aug 27 '15 at 14:50
1

It is not possible. We can't have more than one GET method mapped to the same path. What you can do is :

@GET
@Path("task")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Task> getTask(@QueryParam("id") String uuid){
    if (id == null) {
        return tasks;
    }
    return task(uuid);
}

With the path, you just need to precise in the @Path what you are expecting. For example :

@GET
@Path("task")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Task> getTask(){
    return tasks;
}

@GET
@Path("task/{id}")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Task> getTasks(@PathParam("id") String id){
    return task(uuid);
}
DragonCai
  • 84
  • 5