QueryParam Annotation In Jersey

JAX-RS @QueryParam in Jersey RESTful application implemented in this tutorial . If you have not more idea about restful webservice , then you should read jersey restful web services example . Now we will  discuss about query param example with url .

Example:

http://localhost:8080/JerseyDemo/rest/user/12?p=10

In this example we have p as QueryParam parameter .

Query param in REST service example

@Path("/user")
public class UserHander {

    @GET
    @Path("/{id}")
    public Response addUser(@PathParam("id") int id,@QueryParam("p") int page) {
        System.out.println("id=" + id+"page="+page);
        String str = "id is=" + id+"page="+page;
        return Response.status(Status.OK).entity(str).build();
    }

}

Output:

id is=12page=10

In this example we have send one query path value , But we can send query param multiple values in jax-rs api .

JAX-RS query param multiple values

We can send multiple Comma separated values in query param . We can read these jax-rs query param multiple values in our web service by these methods .In this exmaple we will send queryparam list comma separated. Let’s this is url

http://localhost:8080/JerseyDemo/rest/user/12?city=delhi&country=india&city=california

Jersey supports multiple query parameters with same name and we can map them to a Collection as follows

@GET
@Path("/{id}")
public String addUser(@QueryParam("country") List<String> countryList,
@QueryParam("city") List<String> cityList ) {
      System.out.println("countryList : "+countryList +" , cityList :"+cityList);
 return Response.status(Status.OK).entity("success").build();
}

In second method we will use javax.ws.rs.core.UriInfo to read multiple values of a query paramter in JAX-RS restful web services

@GET 
@Path("/{id}")
 public String addUser( @Context UriInfo uriInfo) {
          List<String> countryList = uriInfo.getQueryParameters().get("country");
          List<String> cityList = uriInfo.getQueryParameters().get("city");
          System.out.println("countryList : "+countryList +" , cityList :"+cityList);
     return Response.status(Status.OK).entity("success").build();
}

This tutorial is part of jersey tutorial for beginner .

Leave a Reply

Your email address will not be published. Required fields are marked *

20 − = 13