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

@MatrixParam Example

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.

For this rest service I decided to create two endpoints. This first endpoint, allows us to add customers to our datastore using matrix parameters. The second endpoint, allows us to view all of the records available to us in the datastore.

The basic format of Matrix parameters in request URL is:

http://localhost:8080/RestfulMatrixParamExample/rest/customer/add;name=IBM; address=100%20Main%20Street;city=Newport;state=Maine;zip=04953

As you can see from the above request URL, this particular web service call will pass in five parameters; first one is name with a value of IBM, address with a value of 100 Main Street (they appear URLEncoded, hence the %20 for spaces), city with a value of Newport, state with a value of Maine, and zip with a value of 04953.

Important Point

The key to remember about Matrix parameters is that key=value pairs are delimited by a semicolon (;) in the request URL.

@MatrixParam 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 matrixparam proj

RESTful Web Service End Points

#URIMethodDescription
1/rest/customer/add?name={name};address={address};city={city};state={state};zip={zip};telephones={t1};telephones={t2};telephones={tN};GETAdds a customer to our datastore by passing in all of the parameters as matrix parameters
2/rest/customer/listGETDisplays all of the customers in our List datastore.

Using the @MatrixParam in JAX-RS API

matrixparam url structure

Single @MatrixParam Parameter

In this illustration you can see how to extract a single matrix parameter from the request URL.

@GET
@Path("/find")
@Produces(MediaType.TEXT_HTML)
public Response findCustomerByName(@MatrixParam("name")  String name) {
  ...
}

Multiple @MatrixParam Parameters

In this illustration you can see how to extract multiple matrix parameters from the request URL.

@GET
@Path("/show")
@Produces(MediaType.TEXT_HTML)
public Response showAllCustomersLimited(@MatrixParam("name")  String name, 
              @MatrixParam("limit")  int max) {
  ...
}

Using List, Set, SortedSet with @MatrixParam Parameter

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

http://localhost:8080/RestfulMatrixParamExample/rest/customer/add;name=IBM; address=100%20Main%20Street;city=Newport;state=Maine;zip=04953;telephones=800-555-1212;telephones=808-545-8181; telephones=888-555-1234

@GET
@Path("/add")
@Produces(MediaType.TEXT_HTML)
public Response addCustomer(@MatrixParam("name")  String name, 
              @MatrixParam("address")  String address,
              @MatrixParam("city")  String city,
              @MatrixParam("state")  String state,
              @MatrixParam("zip")  String zip,
              @MatrixParam("telephones") Set<String> telephones) {
  ...
}

Complete Program using @MatrixParam

package com.avaldes;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

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;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;

import com.avaldes.model.Customer;

@Path("/customer")
public class RestfulMatrixParamExample {
  static Logger logger = Logger.getLogger(RestfulMatrixParamExample.class);
  static List<Customer> customerList = new ArrayList<Customer>(); 
  
  @GET
  @Path("/add")
  @Produces(MediaType.TEXT_HTML)
  public Response addCustomer(@MatrixParam("name")  String name, 
                @MatrixParam("address")  String address,
                @MatrixParam("city")  String city,
                @MatrixParam("state")  String state,
                @MatrixParam("zip")  String zip,
                @MatrixParam("telephones") Set<String> telephones) {

    Customer c = new Customer();
    c.setName(name);
    c.setAddress(address);
    c.setCity(city);
    c.setState(state);
    c.setZip(zip);
    c.setPhones(telephones);
    
    customerList.add(c);
    
    String msg = "addCustomer: " + c.toString();
    logger.info(msg);
    
    return Response.ok(msg).entity(msg).build();
  }
  
  @GET
  @Path("/list")
  public Response getCustomers() {
    
    String msg = "getCustomers: " + customerList;
    logger.info(msg);
    
    return Response.ok(msg).entity(msg).build();
  } 
}

Model Class (Customer.java)

Next we create a model class called Customer.java which will hold all of the values coming from the users entry via the request URL.

package com.avaldes.model;

import java.util.Set;

public class Customer {
  private String name;
  private String address;
  private String city;
  private String state;
  private String zip;
  private Set<String> phones;


  public String getName() {
    return name;
  }
  
  public void setName(String name) {
    this.name = name;
  }
  
  public String getAddress() {
    return address;
  }
  
  public void setAddress(String address) {
    this.address = address;
  }
  
  public String getCity() {
    return city;
  }
  
  public void setCity(String city) {
    this.city = city;
  }
  
  public String getState() {
    return state;
  }
  
  public void setState(String state) {
    this.state = state;
  }
  
  public String getZip() {
    return zip;
  }
  
  public void setZip(String zip) {
    this.zip = zip;
  }
  
    
  public Set<String> getPhones() {
    return phones;
  }

  public void setPhones(Set<String> phones) {
    this.phones = phones;
  }
  
  @Override
  public String toString() {
    return "Customer [name=" + name + ", address=" + address + ", city="
        + city + ", state=" + state + ", zip=" + zip + ", phones="
        + phones + "]";
  }
}

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 will add three customers to our internal datastore using the @MatrixParam parameters. In addition, for the first example, we will also use the @MatrixParam along with a Set of telephones. For the last example, we simply use the /rest/customer/list end point to print out all of the customers that have been added to our datastore.

http://localhost:8080/RestfulMatrixParamExample/rest/customer/add;name=IBM;
address=100%20Main%20Street;city=Newport;state=Maine;zip=04953;telephones=800-555-1212;telephones=808-545-8181; telephones=888-555-1234

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 matrixparam

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

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