Wednesday, December 26, 2012

Hello World Example with Java Rest Web Services

I assume that the reader of this post has prior understanding of GET/POST/PUT/DELETE methods of HTTP.

In order to execute this example, you require the following software and jars files:
Server: Apache Tomcat Server (Any Version)
Jars:
jersey-servlet-1.13.jar
jsr311-api-1.1..jar
asm-3.3.1.jar
jersey-server-1.15.jar
jersey-core-1.15.jar

Class Name: HelloWorldService.java




import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("helloworld")
public class HelloWorldService {
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response printMessage() throws Exception {
return Response.status(200)
.entity("Hello World!, Welcome to JAX-RS programming").build();
}
} // End of HelloWorldService class



Web.xml


<web-app>

         <servlet>
<servlet-name>jaxrsExamples</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jaxrsExamples</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>


Create a .WAR file with this source and web.xml file, either by using ANT or any other build tool and deploy the WAR file into TOMCAT server.

My Tomcat was running at port number 8181 and the name of my WAR file was jaxrs.

Place you WAR file at TOMCAT/webapps location and start your tomcat server.

Then goto Google Chrome browser and type the following address:
http://localhost:8181/jaxrs/helloworld

Output should beHello World!, Welcome to JAX-RS programming



Pity soon, i'll be putting up some more examples on programming with JAX-RS framework.

Akshay Sahu

No comments:

Post a Comment