How can I grab all query parameters in Jersey JaxRS?
JavaJerseyJax RsJava Problem Overview
I am building a generic web service and need to grab all the query parameters into one string for later parsing. How can I do this?
Java Solutions
Solution 1 - Java
You can access a single param via @QueryParam("name")
or all of the params via the context:
@POST
public Response postSomething(@QueryParam("name") String name, @Context UriInfo uriInfo, String content) {
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
String nameParam = queryParams.getFirst("name");
}
The key is the @Context
jax-rs annotation, which can be used to access:
> UriInfo, Request, HttpHeaders, > SecurityContext, Providers
Solution 2 - Java
The unparsed query part of the request URI can be obtained from the UriInfo
object:
@GET
public Representation get(@Context UriInfo uriInfo) {
String query = uriInfo.getRequestUri().getQuery();
...
}
Solution 3 - Java
Adding a bit more to the accepted answer. It is also possible to get all the query parameters in the following way without adding an additional parameter to the method which maybe useful when maintaining swagger documentation.
@Context
private UriInfo uriInfo;
@POST
public Response postSomething(@QueryParam("name") String name) {
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
String nameParam = queryParams.getFirst("name");
}
Solution 4 - Java
we can send value client to server using query parameter like
http://localhost:8080/JerseyDemo/rest/user/12?p=10
Here p is query param value . we can get this value using @QueryParam("p") annotation
public adduser(@QueryParam("p") int page){
//some code
}
Sometime we send list of values in query parameter like
http://localhost:8080/JerseyDemo/rest/user/12?city=delhi&country=india&city=california
In this case we can retrieve all query parameter using @Context UriInfo
public String addUser( @Context UriInfo uriInfo){
List<String> cityList = uriInfo.getQueryParameters().get("city");
}
You can see full example with more details - QueryParam Annotation In Jersey Here you will see more other method for retrieve query parameter in jersey.