jersey

JAX-RS @QueryParam Example

In this example we are going to talk about how you can use @QueryParam annotation to parse URI Query Parameters in a JAX-RS RESTful service.

Basically, @QueryParam denotes that the value of the Query Parameter with the corresponding name will be parsed, and if parsed correctly it will be available on the method argument denoted with@QueryParam.

There are baically two ways to pass parameters in a GET request in REST services. One of them is URI path parameters. We define this parameter with @Path("/{parameter}") annotation on a method. We’ve seen this previouly in JAX-RS @PathParam Example.

In this example we explore the second way to pass parameter, that is Query parameters. For example, to pass “Enjoy” as the value of a query parameter called queryparam, one should follow URLs with a pattern like this: .../bbb?queryparam=Enjoy.

In this example we are not going to focus on how to create JAX-RS application from top to bottom. So make sure you read carefully Jersey Hello World Example and RESTEasy Hello World Example, and pay attention to the sections concerning the creation of the project with Eclipse IDE as well as the deployment of the project in Tomcat.

The code of this tutorial is going to be based on Jersey Hello World Example. You can download the Eclipse project of this tutorial here : JAXRS-HelloWorld.zip

1. Project structure

Let’s remind ourselves the structure of the project we are working on:

project-structure

The code presented in this new tutorial will only concern HelloWorldREST.java file.

At this point you can also take a look at the web.xml file to see how the project is configured:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Restful Web Application</display-name>

	<servlet>
		<servlet-name>jersey-helloworld-serlvet</servlet-name>
		<servlet-class>
                     com.sun.jersey.spi.container.servlet.ServletContainer
                </servlet-class>
		<init-param>
		     <param-name>com.sun.jersey.config.property.packages</param-name>
		     <param-value>com.javacodegeeks.enterprise.rest.jersey</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-helloworld-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

As you can see our servlet is mapped to /rest/ URI pattern. So the basic structure of the URIs used in this example will have the form :

http://localhost:8080/JAXRS-HelloWorld/rest/....

So let’s see how to use @QueryParam annotation.

2. Using @QueryParam annotation

When you want to parse query parameters from a GET request, you can simply define respective arguments to the method that will handle the GET request  and annotate them with @QueryParam annotation. Let’s see how it’s done:

HelloWorldREST.java:

package com.javacodegeeks.enterprise.rest.jersey;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/helloWorldREST")
public class HelloWorldREST {

	@GET
	@Path("/parameters")
	public Response responseMsg( @QueryParam("parameter1") String parameter1, @QueryParam("parameter2") List<String> parameter2) {

		String output = "Prameter1: " + parameter1 + "\nParameter2: " + parameter2.toString();

		return Response.status(200).entity(output).build(); 

	}
}

When you put on your browser:

http://localhost:8080/JAXRS-HelloWorld/rest/helloWorldREST/parameters?parameter1=JCG&parameter2=Examples&parameter2=QueryParameters

Outputs:

Prameter1: JCG
Parameter2: [Examples, QueryParameters]

As you can see, one can put multiple values in the same parameter. All of these values will be parsed an become available in a List.

3. Using @Context annotation

You can use @Context annotation usually to inject contextual Java types related to the request or response. In a JAX-RS application using servlet, ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse objects are available using @Context. Let’s see how you can use it ti inject an UriInfo, an interface that provides access to application and request URI information.

HelloWorldREST.java:

package com.javacodegeeks.enterprise.rest.jersey;

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("/helloWorldREST")
public class HelloWorldREST {

	@GET
	@Path("/parameters")
	public Response responseMsg( @Context UriInfo uriInfo) {

		String parameter1 = uriInfo.getQueryParameters().getFirst("parameter1");

		List<String> parameter2=  uriInfo.getQueryParameters().get("parameter2");

		String output = "Prameter1: " + parameter1 + "\nParameter2: " + parameter2.toString();

		return Response.status(200).entity(output).build(); 
	}
}

When you put on your browser:

http://localhost:8080/JAXRS-HelloWorld/rest/helloWorldREST/parameters?parameter1=JCG&parameter2=Examples&parameter2=QueryParameters

Outputs:

Prameter1: JCG
Parameter2: [Examples, QueryParameters]

4. Setting Default Values Using @DefaultValue annotation

With @DefaultValue annotation, one can define a default value for a query parameter.

HelloWorldREST.java:

package com.javacodegeeks.enterprise.rest.jersey;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.DefaultValue;

@Path("/helloWorldREST")
public class HelloWorldREST {

	@GET
	@Path("/parameters")
	public Response responseMsg(@DefaultValue("Undefined") @QueryParam("parameter1") String parameter1, @QueryParam("parameter2") List<String> parameter2) {

		String output = "Prameter1: " + parameter1 + "\nParameter2: " + parameter2.toString();

		return Response.status(200).entity(output).build(); 

	}
}

When you put on your browser:

http://localhost:8080/JAXRS-HelloWorld/rest/helloWorldREST/parameters?parameter2=Examples&parameter2=09709

Outputs:

Prameter1: Undefined
Parameter2: [Examples, 09709]

Finally, it’s important to note that @QueryParam can only be used on the following Java types:

  • All primitive types except char
  • All wrapper classes of primitive types except Character
  • Have a constructor that accepts a single String argument
  • Any class with the static method named valueOf(String) that accepts a single String argument
  • Any class with a constructor that takes a single String as a parameter
  • List<T>, Set<T>, or SortedSet<T>, where T matches the already listed criteria. Sometimes parameters may contain more than one value for the same name. If this is the case, these types may be used to obtain all values.

This was an example on the usage of JAX-RS @QueryParam annotation.

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rohit C
Rohit C
3 years ago

Excellent post

Back to top button