×
☰ See All Chapters

MatrixParam Example

@MatrixParam allows the rest service consumer to pass the input in service URI. Parameter and value should be separated by = (equals), each parameter value pair should be separated by ; (Semicolon). In this tutorial you will learn to pass the input to rest service and extract the input parameters using @ MatrixParam. Follow the below steps to create the example.

Step 1: Create a dynamic web project.

 matrixparam-0
 

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.

matrixparam-1
 

Step 3: Now create a Restful services using QueryParam annotations.

RestServiceMatrixParam.java

package com.java4coding;

 

import javax.ws.rs.GET;

import javax.ws.rs.MatrixParam;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

 

@Path("/hello")

public class RestServiceMatrixParam {

        @GET

        @Produces(MediaType.TEXT_PLAIN)

        public String sayHello(@MatrixParam("firstName") String firstName, @MatrixParam("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

matrixparam-2
 

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 matrix parameter: https://localhost:8090/JAX_RS_MatrixParamAnnotationExample/rest/hello;firstName=Manu;lastName=Manjunatha

matrixparam-3
 

Without passing matrix parameter: https://localhost:8090/JAX_RS_MatrixParamAnnotationExample/rest/hello

matrixparam-4
 

All Chapters
Author