Gobliins
Gobliins

Reputation: 4026

Jersey multiple get responses on same path possible?

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?

Upvotes: 2

Views: 1926

Answers (2)

Tupac
Tupac

Reputation: 655

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

Upvotes: 3

DragonCai
DragonCai

Reputation: 94

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

Upvotes: 1

Related Questions