In this article, we will learn and implement @MatrixParam annotation in JAX-RS Restful web service. Matrix parameters are set of “key=value” pair with semicolon (;) between them
Jersey is the most popular amongst Restful web service development. Latest Jersey 2.x version has been developed by Oracle/Glassfish team in accordance with JAX-RS 2.0 specification. Earlier Jersey 1.x version was developed and supported by Oracle/Sun team
Latest Jersey release version is 2.12 see here and look documentation and API for details. We will implement Jersey examples in the following articles based on latest 2.x version
Difference between @QueryParam &@MatrixParam
@QueryParam: arguments are supplied in the URL with ampersand sign (&) between each “key=value” pair after the question mark (?)
@MatrixParam: arguments supplied to the URL for the invocation are separated using semicolon (;)
Sample URL for @MatrixParam
http://<server>:<port>/<context-root>/<resteasy-path>/<class-level-path>/<method-level-path>;key1=value1;key2=value2;key3=value3
Look at the above sample URL for @MatrixParam, each pair of “key=value” is separated by semicolon (;)
NOTE: You can skip any “key=value” pair from the request URL while hitting the request and in this case their default values are passed to the method invocation. For example, string – null & int – 0, etc
Annotation Used
- @MatrixParam (ws.rs.MatrixParam)
- @Path (ws.rs.Path)
- @GET (ws.rs.GET)
Technology Used
- Java 1.7
- Eclipse Luna IDE
- Jersey-2.12
- Apache Maven 3.2.1
- Apache Tomcat 8.0.54
- Glassfish-4.1
Mavenize or download required jars
Add Jersey-2.12 dependencies to pom.xml
<properties> <jersey.version>2.12</jersey.version> <jersey.scope>compile</jersey.scope> <compileSource>1.7</compileSource> <maven.compiler.target>1.7</maven.compiler.target> <maven.compiler.source>1.7</maven.compiler.source> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- Jersey core Servlet 2.x implementation --> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet-core</artifactId> <version>${jersey.version}</version> <scope>${jersey.scope}</scope> </dependency> </dependencies>
Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the central repository or maven repository and include them in the classpath
- jersey-container-servlet-core
- javax.ws.rs-api-2.0.1
- jersey-server-2.12
- jersey-common-2.12
- jersey-client-2.12
- jersey-guava-2.12
- javax-annotation-api-1.2
- javax.inject-2.3.0-b10
- hk2-api-2.3.0-b10
- hk2-utils-2.3.0-b10
- aop-alliance-repackaged-2.3.0-b10
- hk2-locator
- javassist-3.18.1-GA
- validation-api-1.1.0.Final
- osgi-resource-locator-1.0.1
Directory Structure
Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE
Maven has to follow certain directory structure
- src/test/java –> test related files, mostly JUnit test cases
- src/main/java –> create java source files under this folder
- src/main/resources –> all configuration files placed here
- src/test/resources –> all test related configuration files placed here
- Maven Dependencies or Referenced Libraries –> includes jars in the classpath
- WEB-INF under webapp –> stores web.xml & other configuration files related to web application
Project Structure (Package Explorer view in Eclipse)
Jars Libraries Used in the Project (Maven Dependencies)
Web application
For any web application, entry point is web.xml which describes how the incoming http requests are served / processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading files particular to project requirements & contains respective listener
With this introduction, we will understand how we configured web.xml for Jersey JAX-RS Restful web service
web.xml (the entry point –> under WEB-INF)
This web.xml file describes,
- Like any JEE web framework register “org.glassfish.jersey.servlet.ServletContainer” with servlet container
- http requests with URL pattern “/rest/*” will be sent to the registered servlet called “jersey-servlet” i.e.; (org.glassfish.jersey.servlet.ServletContainer)
- Set <init-param> with <param-name> as “jersey.config.server.provider.packages” and <param-value> describing the qualified package name of the JAX-RS annotated Resource/Provider classes. In this example, “com.jersey.series.matrixparam”
- <welcome-file-list> files under this tag is the start-up page
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>Jersey-MatrixParam</display-name> <!-- Jersey Servlet --> <servlet> <servlet-name>jersey-servlet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <!-- Register resources and providers --> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.jersey.series.matrixparam</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-servlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <!-- welcome file --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
Let’s see coding in action
URL Pattern
Http url for any common web application is http://<server>:<port>/<root-context>/<from_here_application_specific_path>
In our example, we are going to deploy the war into Tomcat 8.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; Jersey-MatrixParam. Initial path for this application is http://localhost:8080/Jersey-MatrixParam
We have configured “/rest/*” as url-pattern for the “jersey-servlet” servlet in web.xml and at class-level path configured is “/bookservice” using @Path annotation. Next respective path for each method annotated with @Path (method-level)
Book Service interface
Defines two simple abstract methods
- First one takes 1-argument
- Second takes 3-arg arguments
NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately
IBookService.java
package com.jersey.series.matrixparam; import javax.ws.rs.core.Response; public interface IBookService { public Response printBookName(String bookName); public Response printCompleteBookDetails(String bookName, String author, String category); }
Book Service implementation
Implements above interface returning Response object for both method
Defines two simple methods
- First method takes one-argument using @MatrixParam annotation (single parameter)
URL: http://localhost:8080/Jersey-MatrixParam/rest/bookservice/book;name=Biochemistry - Second method takes three-arguments using @MatrixParam annotation (multiple parameters)
URL: http://localhost:8080/Jersey-MatrixParam/rest/bookservice/bookdetail;name=Revenge-of-Microbes;author=Abigail;category=Microbiology
Note: Jersey doesn’t inherit JAX-RS annotations. So we are annotating Resource/Provider classes and then defining qualified package name in web.xml
BookServiceImpl.java
package com.jersey.series.matrixparam; import javax.ws.rs.Consumes; 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; @Path("bookservice") public class BookServiceImpl implements IBookService { // http://localhost:8080/Jersey-MatrixParam/rest/bookservice/book;name=Biochemistry @GET @Path("book") @Consumes({MediaType.TEXT_PLAIN}) @Produces({MediaType.TEXT_PLAIN}) public Response printBookName(@MatrixParam("name") String bookName) { String bookDetail = "Book name is " + bookName; return Response.status(200).entity(bookDetail).build(); } // http://localhost:8080/Jersey-MatrixParam/rest/bookservice/bookdetail;name=Revenge-of-Microbes;author=Abigail;category=Microbiology @GET @Path("bookdetail") @Consumes({MediaType.TEXT_PLAIN}) @Produces({MediaType.TEXT_PLAIN}) public Response printCompleteBookDetails( @MatrixParam("name") String bookName, @MatrixParam("author") String author, @MatrixParam("category") String category) { String bookCompleteDetail = "Book complete detail [Name=" + bookName + ", Author=" + author + ", Category=" + category + "]"; return Response.status(200).entity(bookCompleteDetail).build(); } }
Tomcat-8.0.12 Deployment
- Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
- Copy(ctrl+c) the war file from the target folder
- Paste(ctrl+v) it into apache tomcat (webapps folder)
- Start the tomcat server
Glassfish-4.1 Deployment
- Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
- Once you see “BUILD SUCCESS” after running maven command, keep the war file ready to be deployed
- There are two ways to deploy war file into Glassfish-4.1
- Online
- Offline
- Click here to understand above deployments process in detail
Test the service !!
Testing
There are many ways to do testing
- Access html page from web browser
- Copy the URL of GET service into web browser
- Advanced REST client from Google Chrome
- Rest client in Mozilla Firefox Add On
- Write your own client for example, Java client using improved CloseableHttpClient from Apache
- JDK’s in-built classes like HttpURLConnection
- Using Client, WebTarget from core JAX-RS classes javax.ws.rs.client
1. Hit the web browser with GET URL
First Method:
Enter url http://localhost:8080/Jersey-MatrixParam/rest/bookservice/book;name=Biochemistry
Second Method:
Enter url http://localhost:8080/Jersey-MatrixParam/rest/bookservice/bookdetail;name=Revenge-of-Microbes;author=Abigail;category=Microbiology
2. Using Advanced Rest client from Google Chrome
First Method:
Enter url http://localhost:8080/Jersey-MatrixParam/rest/bookservice/book;name=Biochemistry
Second Method:
Enter url http://localhost:8080/Jersey-MatrixParam/rest/bookservice/bookdetail;name=Revenge-of-Microbes;author=Abigail;category=Microbiology
3. Java client
Uses Client, ClientBuilder, WebTarget and Response classes from core JAX-RS package javax.ws.rs.client for invoking Restful web service
Note: Commented lines will help out us to various request header parameters
TestBookService.java
package test.jersey.series.queryparam; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientConfig; public class TestBookService { public static void main(String[] args) { // setting & invoking first request System.out.println("Executing first service with single parameter"); String httpURL = "http://localhost:8080/Jersey-QueryParam/rest/bookservice/book?name=Neuroscience"; String responseString = testBookService(httpURL); System.out.println("responseString : " + responseString); // setting & invoking second request System.out.println("\n\nExecuting second service with multiple parameter"); String httpURL3 = "http://localhost:8080/Jersey-QueryParam/rest/bookservice/bookdetail?name=Medical-Microbiology&author=Brooks&category=Microbiology"; String responseString3 = testBookService(httpURL3); System.out.println("responseString : " + responseString3); } public static String testBookService(String httpURL) { // local variables ClientConfig clientConfig = null; Client client = null; WebTarget webTarget = null; Builder builder = null; Response response = null; int responseCode; String responseMessageFromServer = null; String responseString = null; try{ // invoke service after setting necessary parameters clientConfig = new ClientConfig(); client = ClientBuilder.newClient(clientConfig); // client.property("Content-Type", MediaType.TEXT_PLAIN); // client.property("accept", MediaType.TEXT_PLAIN); webTarget = client.target(httpURL); // invoke service builder = webTarget.request(MediaType.TEXT_PLAIN).accept(MediaType.TEXT_PLAIN); response = builder.get(); // get response code responseCode = response.getStatus(); System.out.println("Response code: " + responseCode); if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + responseCode); } // get response message responseMessageFromServer = response.getStatusInfo().getReasonPhrase(); System.out.println("ResponseMessageFromServer: " + responseMessageFromServer); // get response string responseString = response.readEntity(String.class); } catch(Exception ex) { ex.printStackTrace(); } finally{ // release resources, if any response.close(); client.close(); } return responseString; } }
Output in console
Executing first service with single parameter Response code: 200 ResponseMessageFromServer: OK responseString : Book name is Neuroscience Executing second service with multiple parameter Response code: 200 ResponseMessageFromServer: OK responseString : Book complete detail [Name=Medical-Microbiology, Author=Brooks, Category=Microbiology]
Conclusion: The URL of the @MatrixParam annotation is much simpler compared to the @QueryParam as there are no question mark (?) and ampersand (&)and this way readability improves much better
Download project
Jersey-2x-MatrixParam (8kB)
Happy Coding !!
Happy Learning !!