I'm newbie on creating web services with Jersey and I'm facing with this problem:
@GET
@Path("/logoutUser")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response logoutUser(@QueryParam("userName") String userName) {
if (userName.equalsIgnoreCase("jmart") || userName.equalsIgnoreCase("jromero")) {
return Response.status(Response.Status.OK).entity("Logout realizado").type(MediaType.APPLICATION_JSON).build();
}else {
throw new CustomNotFoundException("No se ha podido realizar el logout del usuario " + userName);
}
}
@GET
@Path("/logoutUser")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response logoutUser(@QueryParam("idUsuario") int idUsuario) {
if (idUsuario == 1 || idUsuario == 2) {
return Response.status(Response.Status.OK).entity("Logout realizado").type(MediaType.APPLICATION_JSON).build();
}else {
throw new CustomNotFoundException("No se ha podido realizar el logout del usuario " + idUsuario);
}
}
Obviously when I'm trying to call any of the two methods my server throws an exception.
Is there any solution of implementing the same method with different parameter on the same path?
I don't think you can do what you are trying to do with Jersey. Even if you were to switch to an @PathParam it isn't going to give you the control that you are looking for. If I were you though, I wouldn't try to do the conditional logic in Jersey anyway, it is honestly a bit confusing. Instead I would get all the @QueryParams in a list and then look to see if what you want is in that list. See the example here. The other option is to just get both @QueryParams and see which one is null. Since @QueryParams are optional you should check for null anyway. Your new code might look like:
@GET
@Path("/logoutUser")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response logoutUser(@QueryParam("idUsuario") int idUsuario, @QueryParam("userName") String userName) {
if(userName != null) {
//do what you want with the username
}
else if (idUsuario == 1 || idUsuario == 2) {
//do what you want with the id
}
}