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
JBoss RestEasy is a JAX-RS implementation for developing Restful web service in java. Once developed, it isn’t restricted to deploy only in JBoss Application Server but you can deploy in any other server like Apache Tomcat, Glassfish, Oracle Weblogic, etc
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 (javax.ws.rs.MatrixParam)
- @Path (javax.ws.rs.Path)
- @GET (javax.ws.rs.GET)
Technology Used
- Java 1.7
- Eclipse Luna IDE
- RestEasy-3.0.8.Final
- Apache Maven 3.2.1
- Apache Tomcat 7.0.54
- JBoss Application Server 7.1.1.Final
Mavenize or download required jars
Add RestEasy-3.0.8.Final dependencies to pom.xml
<properties> <resteasy.version>3.0.8.Final</resteasy.version> <resteasy.scope>compile</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) --> <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> <!-- RESTEasy JAX RS Implementation --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>${resteasy.version}</version> <scope>${resteasy.scope}</scope> </dependency> <!-- Resteasy Servlet Container Initializer --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-servlet-initializer</artifactId> <version>${resteasy.version}</version> <scope>${resteasy.scope}</scope> </dependency> <!-- RESTEasy JAX RS Client --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-client</artifactId> <version>${resteasy.version}</version> <scope>${resteasy.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
- resteasy-jaxrs
- resteasy-servlet-initializer
- resteasy-client
- jaxrs-api-3.0.8.Final
- jboss-annotations-api_1.1_spec-1.0.1.Final
- jcp-annotations-1.0
- activation-1.1
- async-http-servlet-3.0-3.0.8.Final
- common-codec-1.6
- commons-io-2.1
- commons-logging-1.1.1
- httpcore-4.2.1
- httpclient-4.2.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 RestEasy 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.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher with servlet container
- http requests with URL pattern “/resteasy/*” will be sent to the registered servlet called “javax.ws.rs.core.Application” i.e.; HttpServletDispatcher (org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher)
- set resteasy.servlet.mapping.prefix as <context-param>, if your servlet-mapping has a url-pattern anything other than “/*”. In this example, set “/resteasy”
- if not set, then you will end up with 404 not found error
- set resteasy.resources as <param-name> with comma delimited list of fully qualified JAX-RS resource class names you want to register as <param-value> using global <context-param>
- <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>RestEasy-MatrixParam</display-name> <!-- RestEasy resource registering --> <context-param> <param-name>resteasy.resources</param-name> <param-value>com.resteasy.series.matrixparam.CustomerServiceImpl</param-value> </context-param> <!-- RestEasy Servlet --> <servlet> <servlet-name>javax.ws.rs.core.Application</servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> </servlet> <servlet-mapping> <servlet-name>javax.ws.rs.core.Application</servlet-name> <url-pattern>/resteasy/*</url-pattern> </servlet-mapping> <!-- this is mandatory, if url-pattern is other than /* --> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/resteasy</param-value> </context-param> <!-- 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 7.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; RestEasy-MatrixParam. Initial path for this application is http://localhost:8080/RestEasy-MatrixParam
We have configured “/resteasy/*” as url-pattern for the “javax.ws.rs.core.Application” servlet in web.xml and at interface-level (or say class-level) path configured is “/customer” using @Path annotation. Next respective path for each method annotated with @Path (method-level)
Customer Service interface
Using QueryParam, URL query parameter are mapped into Java method
- First method takes one-argument using @MatrixParam annotation (single parameter)
URL: http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/welcome;custname=Djokovic - Second method takes three-arguments using @MatrixParam annotation (multiple parameter)
URL: http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/custinfo;id=31001;name=Amritraj;age=29
NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately
ICustomerService.java
package com.resteasy.series.matrixparam; import javax.ws.rs.GET; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/customer") public interface ICustomerService { // http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/welcome;custname=Djokovic - Tomcat 7.0.x // http://localhost:9090/RestEasy-MatrixParam/resteasy/customer/welcome;custname=Murray - JBoss AS7 @GET @Path("/welcome") public Response welcomeCustomer(@MatrixParam("custname") String userName); // http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/custinfo;id=31001;name=Amritraj;age=29 - Tomcat 7.0.x // http://localhost:9090/RestEasy-MatrixParam/resteasy/customer/custinfo;id=31002;name=Bopanna;age=28 - JBoss AS7 @GET @Path("/custinfo") public Response printCustomerInfo( @MatrixParam("id") String custId, @MatrixParam("name") String custName, @MatrixParam("age") String custAge); }
Customer Service implementation
Implements above interface returning Response object for both methods
CustomerServiceImpl.java
package com.resteasy.series.matrixparam; import javax.ws.rs.core.Response; public class CustomerServiceImpl implements ICustomerService { public Response welcomeCustomer(String userName) { String welcomeMsg = "Welcome " + userName; return Response.status(200).entity(welcomeMsg).build(); } public Response printCustomerInfo(String custId, String custName, String custAge) { String customerInfo = "Customer [Id=" + custId + ", Name=" + custName + ", Age=" + custAge + "]"; return Response.status(200).entity(customerInfo).build(); } }
Deployment
- Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
- Copy the war file from the target folder
- Paste it into apache tomcat (webapps folder)
- Start the tomcat server
Test the service !!
Testing
There are many ways to do testing
- 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
- Using ResteasyClient, ResteasyWebTarget and Response classes from JBoss package org.jboss.resteasy.client
- Using ClientRequest and ClientResponse classes from JBoss package org.jboss.resteasy.client
1. Hit the web browser with GET URL
First Method:
Enter URL http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/welcome;custname=Djokovic
Second Method:
Enter URL http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/custinfo;id=31001;name=Amritraj;age=29
2. Using Advanced Rest client from Google Chrome
First Method:
Enter URL http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/welcome;custname=Djokovic
Second Method:
Enter URL http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/custinfo;id=31001;name=Amritraj;age=29
3. Java client (RestEasy)
There are two test clients which comes from JBoss RestEasy package org.jboss.resteasy.client and org.jboss.resteasy.client.jaxrs
- ClientRequest and ClientResponse for single parameter invocation
- ResteasyClient, ResteasyClientBuilder and ResteasyWebTarget for multiple parameter invocation
Note: above clients can be interchanged. No restriction, only needs to set correct http request parameters
TestCustomerService.java
package test.resteasy.series.matrixparam; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; public class TestCustomerService { public static void main(String[] args) throws Exception { // setting & invoking first request System.out.println("Executing first service with single parameter"); String url = "http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/welcome;custname=Murray"; String responseString1 = testCustomerServiceForSingleParameter(url); System.out.println("Response String for First Service : " + responseString1); // setting & invoking second request System.out.println("\n\nExecuting second service with multiple parameter"); String url2 = "http://localhost:8080/RestEasy-MatrixParam/resteasy/customer/custinfo;id=31002;name=Bopanna;age=28"; String responseString3 = testCustomerServiceWithMultipleParameters(url2); System.out.println("Response String for Second Service : " + responseString3); } /** * using ClientRequest and ClientResponse classes from org.jboss.resteasy.client * @param url * @throws Exception */ @SuppressWarnings("deprecation") public static String testCustomerServiceForSingleParameter(String url) throws Exception { // local variables ClientRequest clientRequest = null; ClientResponse<String> clientResponse = null; int responseCode; String responseString = null; try{ clientRequest = new ClientRequest(url); clientRequest.setHttpMethod(HttpMethod.GET); clientRequest.accept(MediaType.APPLICATION_FORM_URLENCODED); clientResponse = clientRequest.get(String.class); responseCode = clientResponse.getResponseStatus().getStatusCode(); System.out.println("Response code: " + responseCode); if(clientResponse.getResponseStatus().getStatusCode() != 200) { throw new RuntimeException("Failed with HTTP error code : " + responseCode); } System.out.println("ResponseMessageFromServer: " + clientResponse.getResponseStatus().getReasonPhrase()); responseString = clientResponse.getEntity(); } catch(Exception ex) { ex.printStackTrace(); } finally{ // release resources, if any clientResponse.close(); clientRequest.clear(); } return responseString; } /** * using ResteasyClient, ResteasyWebTarget and Response classes from org.jboss.resteasy.client * @param url */ public static String testCustomerServiceWithMultipleParameters(String url) { // local variables ResteasyClient resteasyClient = null; ResteasyWebTarget resteasyWebTarget = null; Response response = null; int responseCode; String responseString = null; try{ resteasyClient = new ResteasyClientBuilder().build(); resteasyWebTarget = resteasyClient.target(url); response = resteasyWebTarget.request().get(); responseCode = response.getStatus(); System.out.println("Response code: " + responseCode); if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + responseCode); } System.out.println("ResponseMessageFromServer: " + response.getStatusInfo().getReasonPhrase()); responseString = response.readEntity(String.class); } catch(Exception ex){ ex.printStackTrace(); } finally{ // release resources, if any response.close(); } return responseString; } }
Output in console
Executing first service with single parameter Response code: 200 ResponseMessageFromServer: OK Response String for First Service : Welcome Murray Executing second service with multiple parameter Response code: 200 ResponseMessageFromServer: OK Response String for Second Service : Customer [Id=31002, Name=Bopanna, Age=28]
Download project (Tomcat Server 7.0.x)
RestEasy-@MatrixParam-annotation (Tomcat server) (8kB)
JBoss Deployment
- Update pom.xml with resteasy scope “provided” for dependencies as JBoss AS7 modules already contains these dependent jars
<resteasy.scope>provided</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) -->
- Update web.xml
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>RestEasy-MatrixParam</display-name> <!-- RestEasy Servlet --> <servlet-mapping> <servlet-name>javax.ws.rs.core.Application</servlet-name> <url-pattern>/resteasy/*</url-pattern> </servlet-mapping> <!-- welcome file --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
- Rest remain the same
- Read through this article which explains development & deployment of RestEasy web service with JBoss Application Server in detail
Note: JBoss Application Server 7.1.1.Final comes with default RestEasy distribution with version 2.3.2.Final. So update JBoss AS7 with latest RestEasy version. Look at this article, which explains how to update default version with latest version available in the JBoss community
Download project (JBoss Application Server 7.1.1.Final)
RestEasy-@MatrixParam-annotation (JBoss server) (8kB)
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
Happy Coding !!
Happy Learning !!