In this article, we will learn and implement @PathParam annotation in JAX-RS Restful web service. Using @PathParam, you can map/bind values of the URL parameter with formal arguments of the Java method
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
Annotation Used
- @PathParam (javax.ws.rs.PathParam)
- @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
- 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>provided</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)
Note: These jars won’t go inside war file. Only available in the development environment
JBoss RestEasy
As described in the beginning, it is a JAX-RS implementation for developing Restful web service. It’s a JSR 311 specification
There are three approaches available when you are deploying war in JBoss Application Server
- Subclassing javax.ws.rs.core.Application and using @ApplicationPath
- Subclassing javax.ws.rs.core.Application and using web.xml
- Using web.xml (specially, if you don’t want to subclass Application)
A detailed explanation by Stuart Douglas at JBoss JAX-RS Reference guide
We are going to use third approach, as having web.xml is pretty useful when your application is scalable like integrating with other top JEE frameworks like Spring, Struts, Hibernate, etc
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,
- http requests with URL pattern “/resteasy/*” will be sent to the registered servlet called “javax.ws.rs.core.Application” and this in-turn handled by JBoss application server in dispatching request to the correct JAX-RS annotated classes
- <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-PathParam</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>
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 JBoss Application Server 7.1.1.Final server, so our server and port are localhost and 9090 respectively. Context root is the project name i.e.; RestEasy-PathParam. Initial path for this application is http://localhost:9090/RestEasy-PathParam
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 @PathParam, value of the URL parameter are mapped into formal arguments of the Java methods
- First method takes one-argument using @PathParam annotation (single parameter) which its maps to formal argument “custname”
URL: http://localhost:9090/RestEasy-PathParam/resteasy/customer/welcome/Harry
In this case, value “Harry” will be copied to custname argument - Whereas Second method takes three-arguments using @PathParam annotation (multiple parameter)
URL: http://localhost:9090/RestEasy-PathParam/resteasy/customer/custinfo/10001/chris/29
Similarly, 10001 is copied to id argument, “chris” is copied to name argument and “29” is copied to age argument
NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately
ICustomerService.java
package com.resteasy.series.pathparam; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("/customer") public interface ICustomerService { // http://localhost:8080/RestEasy-PathParam/resteasy/customer/welcome/Harry - Tomcat 7.0.x // http://localhost:9090/RestEasy-PathParam/resteasy/customer/welcome/Yuvan - JBoss AS7 @GET @Path("/welcome/{custname}") public Response welcomeCustomer(@PathParam("custname") String userName); // http://localhost:8080/RestEasy-PathParam/resteasy/customer/custinfo/10001/chris/29 - Tomcat 7.0.x // http://localhost:9090/RestEasy-PathParam/resteasy/customer/custinfo/10002/clarke/34 - JBoss AS7 @GET @Path("/custinfo/{id}/{name}/{age}") public Response printCustomerInfo( @PathParam("id") String custId, @PathParam("name") String custName, @PathParam("age") String custAge); }
Customer Service implementation
Implements above interface returning Response object for both methods
CustomerServiceImpl.java
package com.resteasy.series.pathparam; import javax.ws.rs.core.Response; public class CustomerServiceImpl implements ICustomerService { @Override public Response welcomeCustomer(String userName) { String welcomeMsg = "Welcome " + userName; return Response.status(200).entity(welcomeMsg).build(); } @Override 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
- 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 JBoss Application Server 7
- Online
- Offline
Click here to understand above deployments process in detail
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:9090/RestEasy-PathParam/resteasy/customer/welcome/Harry
Second Method:
Enter URL http://localhost:9090/RestEasy-PathParam/resteasy/customer/custinfo/10001/chris/29
2. Using Advanced Rest client from Google Chrome
First Method:
Enter URL http://localhost:9090/RestEasy-PathParam/resteasy/customer/welcome/Harry
Second Method:
Enter URL http://localhost:9090/RestEasy-PathParam/resteasy/customer/custinfo/10001/chris/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.pathparam; 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:9090/RestEasy-PathParam/resteasy/customer/welcome/Yuvan"; String responseString = testCustomerServiceForSingleParameter(url); System.out.println("Response String for First Service : " + responseString); // setting & invoking second request System.out.println("\n\nExecuting second service with multiple parameter"); String url3 = "http://localhost:9090/RestEasy-PathParam/resteasy/customer/custinfo/10002/clarke/34"; String responseString3 = testCustomerServiceWithMultipleParameters(url3); 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 Yuvan Executing second service with multiple parameter Response code: 200 ResponseMessageFromServer: OK Response String for Second Service : Customer [Id=10002, Name=clarke, Age=34]
Conclusion: With @PathParam annotation, you can retrieve URL parameter values appended at the end and map it to the corresponding formal arguments of the Java methods
Few things, before we proceed with RestEasy series
- All the upcoming/following articles in this RestEasy series will be developed/deployed in Apache Tomcat 7.0.54
- Secondly, last section of the following articles in this RestEasy series will explain what are the changes required to deploy and execute/test on the JBoss Application Server 7.1.1.Final environment
Download project
RestEasy-@PathParam-annotation (JBoss AS7) (9kB)
Happy Coding !!
Happy Learning !!