Wednesday, 16 April 2014

REST webservice using jax-rs

In the previous post of SOAP webservice using JAX-WS we explored how to host a SOAP webservice and test it using JAX-WS, here we will host a REST webservice.



Create a web project using maven archetype maven-archetype-webapp.
Below is the structure of the application.
JAX-RS API is implemented by many vendors  like CXF(Apache), ReasEasy(JBOSS), jersey(SUN). We will user the jersey dependency in the application. Add below tag in the pom.xml in dependencies tag.

 <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-server</artifactId>
   <version>1.8</version>
 </dependency>

web.xml


<web-app>
  <display-name>Restful Web Application</display-name>
  <servlet>
  <servlet-name>jersey-serlvet</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.rest</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>


The endpoint class.

package com.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")

public class HelloWorldService {
 
 @GET
 @Path("/{param}")
 public Response getMsg(@PathParam("param") String msg) {
 
  String output = "Hello : " + msg;
 
  return Response.status(200).entity(output).build();
 
 }
 
}

Get the source code from here

After deploying the application in you favorite web server. Open the browser and enter below url in it.

http://localhost:8080/rest-app/rest/hello/hunaid

The output rendered on the browser will be

Hello : hunaid

The same REST webservice can also be tested using Chrome's Advanced REST plugin as shown below


For Web Service Introduction click here

Below are some posts that explain how to implement and test SOAP/REST Webservices

Host
SOAP REST
JAX-WS JAX-RS
Spring-ws Spring-MVC-REST
Client
SOAP REST
JAX-WS(wsimport) Google REST APP
SOAP UI Apache REST

Share the post