RESTful Web Services @QueryParam Example using JAX-RS and Jersey

@QueryParam Example

In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract query parameters from the request URL using the @QueryParam annotation.

This rest service uses the same methods we developed in the last tutorial, RESTful Web Services @PathParam Example, which calculates square root of a number by extracting the value from the path using @QueryParam annotation. The thing that differentiates this tutorial from the last is that we have also added a calcSumAllValues method that extracts a List of @QueryParam values from the request URL.

The basic format of Query parameters in request URL is:

http://localhost:8080/RestfulQueryParamExample/rest/client/name=Alex&age=22&state=Ohio

As you can see from the above request URL, this particular web service call will pass in three parameters; first one is name with a value of Alex, age with a value of 22, and state with a value of Ohio.

Important Point

The key to remember about Query parameters is that key=value pairs are delimited by an ampersand (&) in the request URL.

@QueryParam can be used only on the following Java types:

  • All primitive types except char
  • All wrapper classes of primitive types except Character
  • Any class with a constructor that accepts a single Stringargument
  • Any class with the static method named valueOf(String) that accepts a single Stringargument
  • 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

Getting Started

In order to run this tutorial yourself, you will need the following:

  • Java JDK 1.6 or greater
  • Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
  • Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
  • Jersey JAX-RS
  • log4J (for logging purposes)

Required Libraries

Copy all of the following jars to WebContent->WEB-INF->lib folder.

asm-3.1.jar
jersey-client-1.18.jar
jersey-core-1.18.jar
jersey-json-1.18.jar
jersey-server-1.18.jar
jersey-servlet-1.18.jar
jsr311-api-1.1.1.jar
log4j-1.2.17.jar

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

jax-rs queryparam proj

RESTful Web Service End Points

#URIMethodDescription
1/rest/calculate/squareroot?value={v1}GETCalculates the square root of a number denoted by v1
2/rest/calculate/add?value1={v1}&value2={v2}GETAdds the numbers denoted by v1 and v2
2/rest/calculate/subtract?value1={v1}&value2={v2}GETSubtracts the numbers denoted by v1 and v2
2/rest/calculate/sum?values={v1}&values={v2}&values={v3}…&values={vN}GETSum all the numbers denoted by v1 ~ vN repeating pattern

Using the @QueryParam in JAX-RS API

queryparam url structure

Single @QueryParam Parameter

In this example we show you how to extract a single query parameter from the request URL.

@GET
@Path("/squareroot")
@Produces(MediaType.TEXT_HTML)
public Response calcSqrt(@QueryParam("value") int value) {

  double answer = Math.sqrt(value);
  String msg = String.format("calcSqrt==> value: %d, answer: %10.4f", value, answer);
  logger.info(msg);
    
  return Response.status(200).entity(msg).build();
}

Multiple @QueryParam Parameters

In this example we show you how to extract a multiple query parameters from the request URL.

@GET
@Path("/add")
@Produces(MediaType.TEXT_HTML)
public Response calcAddTwoValues(@QueryParam("value1")  double value1, 
                                 @QueryParam("value2")  double value2) {

  double answer = value1 + value2;
  String msg = String.format("calcAddTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", 
                              value1, value2, answer);
  logger.info(msg);
    
  return Response.status(200).entity(msg).build();
}

Using List, Set, SortedSet with @QueryParam Parameter

In this example we show you how to extract a List of @QueryParam values from the request URL. You could quite as easily use Set or Sorted as well. By using the List<Integer> values it will automatically be converted into the List collection for us.

@GET
@Path("/sum")
@Produces(MediaType.TEXT_HTML)
public Response calcSumAllValues(@QueryParam("values") List<Integer> values) {

  double answer = 0;
  for (int v: values) {
    answer += v;
  }
  String msg = String.format("calcSumAllValues==> values: %s, answer: %10.4f", 
                             values.toString(), answer);
  logger.info(msg);
    
  return Response.status(200).entity(msg).build();
}

Complete Program using @QueryParam

package com.avaldes;

import java.util.List;

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;

import org.apache.log4j.Logger;

@Path("/calculate")
public class RestfulQueryParamExample {
  static Logger logger = Logger.getLogger(RestfulQueryParamExample.class);
  
  @GET
  @Path("/squareroot")
  @Produces(MediaType.TEXT_HTML)
  public Response calcSqrt(@QueryParam("value") int value) {

    double answer = Math.sqrt(value);
    String msg = String.format("calcSqrt==> value: %d, answer: %10.4f", value, answer);
    logger.info(msg);
    
    return Response.status(200).entity(msg).build();
  }
  
  @GET
  @Path("/add")
  @Produces(MediaType.TEXT_HTML)
  public Response calcAddTwoValues(@QueryParam("value1")  double value1, 
                                   @QueryParam("value2")  double value2) {

    double answer = value1 + value2;
    String msg = String.format("calcAddTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", 
                  value1, value2, answer);
    logger.info(msg);
    
    return Response.status(200).entity(msg).build();
  }
  
  @GET
  @Path("/sub")
  @Produces(MediaType.TEXT_HTML)
  public Response calcSubTwoValues(@QueryParam("value1")  double value1, 
                                   @QueryParam("value2")  double value2) {

    double answer = value1 - value2;
    String msg = String.format("calcSubTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", 
                  value1, value2, answer);
    logger.info(msg);
    
    return Response.status(200).entity(msg).build();
  }

  @GET
  @Path("/sum")
  @Produces(MediaType.TEXT_HTML)
  public Response calcSumAllValues(@QueryParam("values") List<Integer> values) {

    double answer = 0;
    for (int v: values) {
      answer += v;
    }
    String msg = String.format("calcSumAllValues==> values: %s, answer: %10.4f", 
                  values.toString(), answer);
    logger.info(msg);
    
    return Response.status(200).entity(msg).build();
  }
}

Web Deployment Descriptor (web.xml)

This is a pretty straight forward deployment descriptor file – only thing you need to add is the location of you java package in the Jersey ServletContainer entry as init-param. Please ensure you add it to the web.xml file as shown below.

<?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>com.omega.rest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
 
   <servlet-name>Jersey REST Service</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.avaldes</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Testing out the Web Services

In this example, we add two numbers using the web service using multiple @QueryParam parameters.

queryparam add

This next example we calculate the sum of all values in a repeating list of values using @QueryParam parameter.

queryparam sum

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java jaxrs queryparam

Related JAX-RS Tutorial Posts

  • RESTful Web Services with AngularJS, Bootstrap and Java using JAX-RS and Jersey
    In this tutorial we will develop a full blown CRUD application using JAX-RS API and Jersey to implement RESTful web services. JAX-RS stands for Java API for RESTful Web Services and by using this powerful API developers can easily build REST services. Jersey RESTful Web Services is an open source framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs.
  • JAX-RS Security using JSON Web Encryption(JWE) with AngularJS, Bootstrap, Grid-UI and MongoDB Example
    In this tutorial we will discuss how to use AngularJS, Bootstrap and Grid-UI to connect to secure JAX-RS RESTful web services using JWE/JWT/JWS for Authentication and Authorization. In our example implementation, we will be using Symmetric Encryption where the receiver and sender share a common key.
  • JAX-RS Security using JSON Web Encryption (JWE) with JWS/JWT for Authentication and Authorization
    In this tutorial we will discuss how to secure JAX-RS RESTful web services using JSON Web Encryption(JWE), JSON Web Key (JWK), JSON Web Signature(JWS), and JSON Web Tokens(JWT) for Authentication and Authorization. JSON Web Encryption (JWE) encrypted content using Javascript Object Notation (JSON) based structures.
  • JAX-RS Security using JSON Web Tokens (JWT) for Authentication and Authorization
    In this tutorial we will discuss how to secure JAX-RS RESTful web services using JSON Web Tokens Authentication and Authorization. This form of security is used for authenticating a client using a signed token which can be verified by application servers. This token-based form of security is a ideal candidate for Cross-domain (CORS) access and when server-side scalability is a prime motivation factor.
  • JAX-RS Security using API-KEY for Authorization
    In this tutorial we will discuss how to secure JAX-RS RESTful web services using API-KEY or Service Key for Authorization. This form of security is used to ensure that certain RESTful endpoints are protected against unauthorized use.
  • JAX-RS Security using Digest Authentication and Authorization
    In this JAX-RS Digest Authentication and Authorization tutorial we will discuss how to set up digest security for our RESTful web service. This form of access authentication is slightly more complex than the previously discussed JAX-RS Basic Authentication Tutorial.
  • JAX-RS Security using Basic Authentication and Authorization
    In this JAX-RS basic authentication and authorization tutorial we will discuss how to set up security for our RESTful web service. We will need to ensure that some of the URIs are protected and only clients that have been authenticated and authorized are able to gain access and make use of them.
  • Upload and Download Multiple Binary Files using MongoDB
    In this tutorial we are going to develop multiple file upload and file download capability using RESTful web service using JAX-RS and Jersey storing the contents of files into MongoDB Database using a powerful feature in MongoDB for managing large files called GridFS.
  • Inserting and Retrieving Binary Data with MongoDB using JAX-RS RESTful Web Service
    In this tutorial we are going to develop file upload and file download capability using RESTful web service using JAX-RS and Jersey storing the contents of files into MongoDB Database using a powerful feature in MongoDB for managing large files called GridFS. The bulk of the framework for this tutorial came from my previous tutorial so you find many similarities between the two posts.
  • Inserting and Retrieving Binary Data with SQL Server Database using JAX-RS RESTful Web Service
    In this tutorial we are going to develop file upload and file download capability using RESTful web service using JAX-RS and Jersey storing the contents of the file into SQL Server Database using BLOB. Our example will be able to store PDF files, Excel files, Word Document files, Powerpoint files, Image files, or any other type of file available us provided we have ample amount of storage space.
  • File Download Example Using RESTful Web Service with JAX-RS and Jersey
    In this example we are going to develop file download capability using RESTful web service using JAX-RS and Jersey. As you will see, downloading a File using Jersey is very easy as it uses the HTTP GET for the file operations. In our web service, we will be allowing you to download the file via two mechanisms. You will be able to download by HTTP query parameters via @QueryParam and also by using the path parameters via @PathParam.
  • JAX-RS Restful Web Services with JNDI Datasource for MySQL in Tomcat
    In this tutorial we will discuss how to set up JAX-RS RESTful web services and configure a JNDI Datasource with Connection Pooling in Tomcat and connect to MYSQL Database. JNDI (Java Naming and Directory Interface) provides and interface to multiple naming and directory services.
  • File Upload Example Using RESTful Web Service with JAX-RS and Jersey
    In this example we are going to develop file upload capability using RESTful web service using JAX-RS and Jersey. As you will see, uploading a File using Jersey is pretty straight forward as it uses HTTP POST with the encoding type of multipart/form-data for the file operations.
  • RESTful Web Services @FormParam Example using JAX-RS and Jersey
    In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract form parameters submitted by a form using @FormParam annotation.
  • RESTful Web Services @MatrixParam Example using JAX-RS and Jersey
    In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract matrix parameters from the request URL using the @MatrixParam annotations.
  • RESTful Web Services @QueryParam Example using JAX-RS and Jersey
    In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract query parameters from the request URL using the @QueryParam annotation.
  • RESTful Web Services @PathParam Example using JAX-RS and Jersey
    In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract path parameters from the request URL using the @PathParam annotation.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *