Search code examples
javajsonjerseyjax-rspath-parameter

How to use "?" no get Path Rest?


I am developing a rest server in java, netbeans. I have my GET request:

//myip/application/v1/cardapio/id=1

@Stateless
@Path("v1/cardapio")
public class CardapioResource {
        @GET
        @Produces("application/json")
        @Path("id={id}")
        public String getCardapio(@PathParam("id") int id) {

            JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
            JsonObject obj = new JsonObject();
            obj.add("dados", array);
            return obj.toString();
        }
}

It works correctly.

But I want to do differently, as I saw in other examples, I want to mark the beginning of the variables with the "?".

Ex: //myip/application/v1/cardapio/?id=1

    @Stateless
    @Path("v1/cardapio")
    public class CardapioResource {
            @GET
            @Produces("application/json")
            @Path("?id={id}")
            public String getCardapio(@PathParam("id") int id) {

                JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
                JsonObject obj = new JsonObject();
                obj.add("dados", array);
                return obj.toString();
            }
    }

Thus error 404, page not found.


Solution

  • What you seen in "other examples" is just normal usage of URL's query part. Just use it with @Queryparam

       @Stateless
        @Path("v1/cardapio")
        public class CardapioResource {
                @GET
                @Produces("application/json")
                @Path("/") // can be removed actually
                public String getCardapio(@QueryParam("id") int id) {
    
                    JsonArray array = (JsonArray) gson.toJsonTree(ejb.findById(id));
                    JsonObject obj = new JsonObject();
                    obj.add("dados", array);
                    return obj.toString();
                }
        }
    

    Here you are mapping getCardapio to v1/cardapio/ and you will try to get id from query string so

    Ex: //myip/application/v1/cardapio/?id=1

    will just work.