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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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>
<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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!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>
<!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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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();
        
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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();
        
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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();
        
    }
 
 
}
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

Karibasappa G C (KB)
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