JAX-RS @QueryParam , @DefaultValue and @Context with example


What is QueryParam ?

Before understanding QueryParam, we need to know about Query String.

What is Query String ?

It is basically a part of URL which contains the values in the key value form.
It specifies these values after the question mark(?) in the URL and multiple key values are separated by “&”.

Example:

http://sample.com?id=1&name=kb

In the above URL, after ‘?’ we can see 2 key value pairs id=1 and name=kb
These key values are called query String.

What is QueryParam?

It is same as Query string, but in JAX-RS we have the annotation to read this query string and that annotation name is “QueryParam”.

We write it as @QueryParam.

This annotation will be used at the method argument level.

If there are multiple key value pairs in the URL then we need to use @QueryParam multiple times (one for each key value pair)

For the above example, we can use it as below

(@QueryParam(“id”) String id,@QueryParam(“name”) String name, . . . . )

Let’s see the complete example on this

Create a new Maven Web project in eclipse (Refer Rest service Hello World project for the same)

Project structure

Project structure

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>JAXRSQueryParam</groupId>
  5.   <artifactId>JAXRSQueryParam</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>JAXRSQueryParam Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <dependencies>
  11.     <dependency>
  12.       <groupId>junit</groupId>
  13.       <artifactId>junit</artifactId>
  14.       <version>3.8.1</version>
  15.       <scope>test</scope>
  16.     </dependency>
  17.     <dependency>
  18.     <groupId>org.glassfish.jersey.containers</groupId>
  19.     <artifactId>jersey-container-servlet</artifactId>
  20.     <version>2.24</version>
  21. </dependency>
  22.   </dependencies>
  23.   <build>
  24.     <finalName>JAXRSQueryParam</finalName>
  25.   </build>
  26. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JAXRSQueryParam</groupId>
  <artifactId>JAXRSQueryParam</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>JAXRSQueryParam Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.24</version>
</dependency>
  </dependencies>
  <build>
    <finalName>JAXRSQueryParam</finalName>
  </build>
</project>

We have added dependencies for Jersey servlet and Junit in the above pom file.

Step 2

Update web.xml file with Jersey servlet container

  1. <!DOCTYPE web-app PUBLIC
  2.  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3.  "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4.  
  5. <web-app>
  6.   <display-name>Archetype Created Web Application</display-name>
  7.   <servlet>
  8.         <servlet-name>jersey-serlvet</servlet-name>
  9.          <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  10.         <init-param>
  11.             <param-name>jersey.config.server.provider.packages</param-name>
  12.             <param-value>com.kb.rest</param-value>
  13.         </init-param>
  14.         <load-on-startup>1</load-on-startup>
  15.     </servlet>
  16.  
  17.     <servlet-mapping>
  18.         <servlet-name>jersey-serlvet</servlet-name>
  19.         <url-pattern>/rest/*</url-pattern>
  20.     </servlet-mapping>
  21. </web-app>
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		 <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
		<init-param>
			<param-name>jersey.config.server.provider.packages</param-name>
			<param-value>com.kb.rest</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

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

we have defined a special servlet called “jersey-serlvet” in web.xml and mapped it by the URL pattern /rest/*
Any request matching the above pattern will be handled by jersey Servlet.

Step 3

Create the rest service class which will serve our request

  1. package com.kb.rest;
  2.  
  3. import javax.ws.rs.GET;
  4. import javax.ws.rs.Path;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.QueryParam;
  7. import javax.ws.rs.core.MediaType;
  8. import javax.ws.rs.core.Response;
  9.  
  10. @Path("/userDetails")
  11. public class QueryParamUserService {
  12.  
  13.     @GET
  14.     @Produces("text/html")
  15.     public Response getUserDetails(@QueryParam("name") String name,@QueryParam("state") String state,@QueryParam("gender") String gender){
  16.         String output =null;
  17.         String title=null;
  18.         if("M".equals(gender)){
  19.             title="Mr";
  20.         }
  21.         else{
  22.             title="Mrs";
  23.         }
  24.         if("AP".equals(state)){
  25.             output =title+" "+name+" is from INDIA country";
  26.         }
  27.        
  28.         else if("NY".equals(state)){
  29.             output =title+" "+name+" is from USA country";
  30.         }
  31.         else{
  32.             output =title+" "+name+" is from Unknown country";
  33.         }
  34.        
  35.         return Response.status(200).entity(output).build();
  36.        
  37.     }
  38. }
package com.kb.rest;

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

@Path("/userDetails")
public class QueryParamUserService {

	@GET
	@Produces("text/html")
	public Response getUserDetails(@QueryParam("name") String name,@QueryParam("state") String state,@QueryParam("gender") String gender){
		String output =null;
		String title=null;
		if("M".equals(gender)){
			title="Mr";
		}
		else{
			title="Mrs";
		}
		if("AP".equals(state)){
			output =title+" "+name+" is from INDIA country";
		}
		
		else if("NY".equals(state)){
			output =title+" "+name+" is from USA country";
		}
		else{
			output =title+" "+name+" is from Unknown country";
		}
		
        return Response.status(200).entity(output).build();
		
	}
}

In this Rest service, we are passing 3 query parameters name, gender and state in the URL and we have written a logic to get the user details based on these parameters.

Step 4

Build and deploy the project

Step 5

Let’s see the output

Access below URL
http://localhost:8080/JAXRSQueryParam/rest/userDetails?name=John&state=NY&gender=M

output1

Access below URL
http://localhost:8080/JAXRSQueryParam/rest/userDetails?name=John&state=AP&gender=F

output2

We can see that our output has retrieved user details based on parameters passed in the query.

@DefaultValue


Sometimes we get the query parameters as null whenever they have not been passed in the URL,In that case,@DefaultValue annotation becomes handy.

It’s good to use Default values always for the Query Params as below

  1. package com.kb.rest;
  2.  
  3. import javax.ws.rs.DefaultValue;
  4. import javax.ws.rs.GET;
  5. import javax.ws.rs.Path;
  6. import javax.ws.rs.Produces;
  7. import javax.ws.rs.QueryParam;
  8. import javax.ws.rs.core.Response;
  9.  
  10. @Path("/userDetailsDefaultValueQueryParam")
  11. public class DefaultValueQueryParamUserService {
  12.  
  13.     @GET
  14.     @Produces("text/html")
  15.     public Response getUserDetails(@DefaultValue("John") @QueryParam("name") String name,@DefaultValue("NY") @QueryParam("state") String state,@DefaultValue("M") @QueryParam("gender") String gender){
  16.         String output =null;
  17.         String title=null;
  18.         if("M".equals(gender)){
  19.             title="Mr";
  20.         }
  21.         else{
  22.             title="Mrs";
  23.         }
  24.         if("AP".equals(state)){
  25.             output =title+" "+name+" is from INDIA country";
  26.         }
  27.        
  28.         else if("NY".equals(state)){
  29.             output =title+" "+name+" is from USA country";
  30.         }
  31.         else{
  32.             output =title+" "+name+" is from Unknown country";
  33.         }
  34.        
  35.         return Response.status(200).entity(output).build();
  36.        
  37.     }
  38. }
package com.kb.rest;

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

@Path("/userDetailsDefaultValueQueryParam")
public class DefaultValueQueryParamUserService {

	@GET
	@Produces("text/html")
	public Response getUserDetails(@DefaultValue("John") @QueryParam("name") String name,@DefaultValue("NY") @QueryParam("state") String state,@DefaultValue("M") @QueryParam("gender") String gender){
		String output =null;
		String title=null;
		if("M".equals(gender)){
			title="Mr";
		}
		else{
			title="Mrs";
		}
		if("AP".equals(state)){
			output =title+" "+name+" is from INDIA country";
		}
		
		else if("NY".equals(state)){
			output =title+" "+name+" is from USA country";
		}
		else{
			output =title+" "+name+" is from Unknown country";
		}
		
        return Response.status(200).entity(output).build();
		
	}
}

We have provided the default values for each of the query param in the method.

This way we can handle gracefully if parameters are not passed in the URL.

Access the below url to see how @DefaultValue works
http://localhost:8080/JAXRSQueryParam/rest/userDetailsDefaultValueQueryParam

output3

We can see that in the URL, we have not passed any parameters, but all the parameters have got the default values

@Context UriInfo


We can also get the query parameters programmatically without using @QueryParam.

We just need to use @Conext UriInfo uriInfo as the method argument as below

  1. package com.kb.rest;
  2.  
  3. import javax.ws.rs.GET;
  4. import javax.ws.rs.Path;
  5. import javax.ws.rs.Produces;
  6. import javax.ws.rs.QueryParam;
  7. import javax.ws.rs.core.Context;
  8. import javax.ws.rs.core.Response;
  9. import javax.ws.rs.core.UriInfo;
  10.  
  11. @Path("/userDetailsUriInfo")
  12. public class ContextUriInfoUserService {
  13.  
  14.     @GET
  15.     @Produces("text/html")
  16.     public Response getUserDetails(@Context UriInfo uriInfo){
  17.         String name=uriInfo.getQueryParameters().getFirst("name");
  18.         String state=uriInfo.getQueryParameters().getFirst("state");
  19.         String gender=uriInfo.getQueryParameters().getFirst("gender");
  20.         String output =null;
  21.         String title=null;
  22.         if("M".equals(gender)){
  23.             title="Mr";
  24.         }
  25.         else{
  26.             title="Mrs";
  27.         }
  28.         if("AP".equals(state)){
  29.             output =title+" "+name+" is from INDIA country";
  30.         }
  31.        
  32.         else if("NY".equals(state)){
  33.             output =title+" "+name+" is from USA country";
  34.         }
  35.         else{
  36.             output =title+" "+name+" is from Unknown country";
  37.         }
  38.        
  39.         return Response.status(200).entity(output).build();
  40.        
  41.     }
  42.  
  43.  
  44. }
package com.kb.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/userDetailsUriInfo")
public class ContextUriInfoUserService {

	@GET
	@Produces("text/html")
	public Response getUserDetails(@Context UriInfo uriInfo){
		String name=uriInfo.getQueryParameters().getFirst("name");
		String state=uriInfo.getQueryParameters().getFirst("state");
		String gender=uriInfo.getQueryParameters().getFirst("gender");
		String output =null;
		String title=null;
		if("M".equals(gender)){
			title="Mr";
		}
		else{
			title="Mrs";
		}
		if("AP".equals(state)){
			output =title+" "+name+" is from INDIA country";
		}
		
		else if("NY".equals(state)){
			output =title+" "+name+" is from USA country";
		}
		else{
			output =title+" "+name+" is from Unknown country";
		}
		
        return Response.status(200).entity(output).build();
		
	}


}

It is good to use @Context whenever we are passing multiple parameters as part of URL.

Access the below url to see how @Context UriInfo works
http://localhost:8080/JAXRSQueryParam/rest/userDetailsUriInfo?name=John&state=AP&gender=F

output4

Download this project JAXRSQueryParam.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on