How to create simple REST web service using jersey
- Thursday, May 2, 2013, 17:22
- Web service
- 18,021 views
In this tutorial I will demonstrate you what Rest is and how to develop a simple rest web service in java using jersey. Before moving forward let see what rest is.
- REST stands for Representational State Transfer. (It is sometimes spelled “ReST”.)
- It relies on a stateless, client-server, cacheable communications protocol which uses HTTP protocol.
- REST is a simpler, lightweight alternative to RPC (Remote Procedure Calls) and Web Services (SOAP, WSDL, etc). Know more different between Rest and SOAP.
I will use sun’s JAX-RS reference implementation Jersey to demonstrate simple greeting service.
Create new Java EE project in eclipse and add all dependent jar files in classpath. You can download related jars from https://jersey.java.net site.
Your web.xml will look similar to …
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>RESTfulTest</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>org.techzoo.restful</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> |
Here you can see web.xml
contain one servlet named ServletContainer
which has url pattern associated to it.
Now write one class which is our main REST web service class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package org.techzoo.restful; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("/greeting") public class GreetingService { @GET @Path("/{name}") public Response sayGreeting(@PathParam("name") String msg) { String output = String.format("Greeting to %s from Jersey", msg); return Response.status(200).entity(output).build(); } } |
This REST based web service will be accessable using following URL.
http://localhost:8080/RESTfulTest/rest/greeting/tousif