☰ See All Chapters |
QueryParam Example
@QueryParam allows the rest service consumer to pass the input in service URI as a query string Parameters should be sent as query string in URL. Query string should start with? (Question Mark), parameter and value should be separated by = (equals), each parameter value pair should be separated by & (Ampersand). In this tutorial you will learn to pass the input to rest service and extract the input parameters using @QueryParam. Follow the below steps to create the example.
Step 1: Create a dynamic web project.
Step 2: Add Jersey implementation Jars by downloading from the following location.
(Google search key word “jax rs jersey jar download”)
https://jersey.github.io/download.html
Or click here to download the jars that we have used.
Now we will get jaxrs-ri-2.28.zip, extract the zip file. Copy all the jars present in lib, ext and api directories into “WebContent/WEB-INF/ lib” directory of project.
Step 3: Now create a Restful services using QueryParam annotations.
RestServiceQueryParam.java
package com.java4coding;
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;
@Path("/hello") public class RestServiceQueryParam { @GET @Produces(MediaType.TEXT_PLAIN) public String sayHello(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName) { return "Hello " + firstName+ " "+ lastName; } } |
Step 5: In web.xml, configure service as below.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/j2ee" xmlns:web="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4"> <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.java4coding</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> |
Final project directory structure is
Step 5: Deploy the project to any server (Let’s consider Tomcat), Just right click on the project >Run As > Run on Server >Select Tomcat server.
Open below URL in browser. (Change the project name and port number according to your setup)
With query parameter: https://localhost:8090/JAX_RS_QueryParamAnnotationExample/rest/hello?firstName=Manu&lastName=Manjunatha
Without passing query parameter: https://localhost:8090/JAX_RS_QueryParamAnnotationExample/rest/hello
All Chapters