0

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.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • *But I want to do differently, as I saw in other examples, I want to mark the beginning of the variables* you just saw normal usage of query params. It is not part of controller routing. IMHO `@Path("id={id}")` is not what you want. You jsut want to map to `/` and get `@QueryParam` – Antoniossss Aug 08 '19 at 14:54
  • @Antoniossss But there is a way to do it, I've seen several cases. I just believe I'm on the wrong track. – Júlio César Bindandi Aug 08 '19 at 14:58
  • Yes, you are trying to misuse url construct. You want (for whatever reasons) query string to be part of path. – Antoniossss Aug 08 '19 at 14:59

3 Answers3

1

You can't, after ? sign it's query parameters and not path parameters

You can use @QueryParam("id")

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
1

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.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

You can also use @RequestParam("id") int id

Doctor Who
  • 747
  • 1
  • 5
  • 28