How to read multiple values of a query paramter in JAX-RS restful web services?
In the previous example we have seen how to read query paramters from the request using @QueryParam annotation. What if the
user request is in the below format? same id with multiple values?
http://localhost:8080/RestfulWebServices/employee/query?id=1016&id=1017&id=1415
In the above URL, the id value is same, but with different values, this can be easily readable as a list of values using UriInfo object.
In the previous examples we have given details of application setup, dependencies, web.xml file configurations: If you want to
know about these configuration, please refer these:
Restful web services using RESTEasy hello world example.
Restful web services using Jersey hello world example.
Look at the below class which shows how to read multiple values with a unique request parameters:
package com.java2novice.restful;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@Path("/employee")
public class QueryParamExampleService {
@GET
@Path("/query")
public Response getEmployeeQuery(@Context UriInfo uriInfo){
/** read complete employee id list from request query parameter**/
List<String> empIdList = uriInfo.getQueryParameters().get("id");
System.out.println("Received List: "+empIdList);
/** read first employee id from request query parameter **/
String firstEmpId = uriInfo.getQueryParameters().getFirst("id");
System.out.println("First emp record from the request: "+firstEmpId);
return Response.status(200).entity("processed request").build();
}
}
|
In the above example, if you use "/employee/query?id=1016&id=1017&id=1415" URI pattern with query parameters,
here is the output:
|