Tuesday, March 22, 2011

REST Webservices in Java

Preparing and Executing a simple REST Webservice using Tomcat and MyEclipse:

1) Create a new WebService Project and name it "RestWebService2".
2) Create a package "model" and create a java file "HelloWorldService.java". This is basically your webservice. 
Contents are shown below.
3) Add some contents into "WEB-INF/web.xml", contents are shown below.
4) Add a new "sun-jaxws.xml" file inside "WEB-INF/" directory.
5) Run your application in Tomcat. In MyEclipse it is in-built, so just right click on project and Choose
"Run as"--> Server application (then choose Tomcat). It will show the browser with Index.jsp (default JSP
page contents in browser).
6) How to hit URL and what you will get as output is also mentioned at the end.
7) This is a basic example, once you run successfully, you can read further in other sites.
8) This is a tested example, works fine for me.

package model;
import javax.annotation.Resource;

import java.io.ByteArrayInputStream;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import javax.xml.ws.BindingType;
import javax.xml.ws.Provider;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPBinding;
import javax.xml.ws.http.HTTPException;

public class HelloWorldService implements Provider<Source> {

protected WebServiceContext context;

public Source invoke(Source source) {
try {
MessageContext mc = context.getMessageContext();

String queryString = (String)mc.get(MessageContext.QUERY_STRING);
String pathInfo = (String)mc.get(MessageContext.PATH_INFO);

if (queryString != null && queryString.contains("name=")) {
return sayHello(queryString);
} else if (pathInfo != null && pathInfo.contains("/name")) {
return sayHello(pathInfo);
} else {
return sayHello("Unknown");
} catch(Exception e) {
throw new HTTPException(500);

private Source sayHello(String name) {
Source source = new StreamSource(
new ByteArrayInputStream((new String("<result>Hello Client, Response from Rest Webservice : "+name+"</result>")).getBytes()));
return source;

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"


<?xml version="1.0" encoding="UTF-8"?>

<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
<endpoint name="helloWorld" implementation="model.HelloWorldService"
url-pattern="/hello/*" />

It can have anything here.... no use....

URL Hit:
<result>Hello Client, Response from Rest Webservice : name=deepakKumarmodi</result> 

URL Hit:
<result>Hello Client, Response from Rest Webservice : /name/deepakKumarmodi</result> 

URL Hit (Any other non matching pattern):
<result>Hello Client, Response from Rest Webservice : Unknown</result> 


No comments:

Post a Comment