Hello World REST

Writing Hello World REST Webservice


  • Open eclipse. Create a new Dynamic web project. Name it as HelloWorldRS
  • Under Java resources create a package a called com.example
  • UnderWebContent-> WEB-INF create a file web.xml
  • Under WebContent->WEB-INF->lib add the jars under api, lib, ext directories of jersey bundle downloaded in tools section.

Web.xml
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>Restful Web Application</display-name>

 <servlet>
  <servlet-name>jersey-serlvet</servlet-name>
  <servlet-class>
                     org.glassfish.jersey.servlet.ServletContainer
                </servlet-class>
  <init-param>
       <param-name>jersey.config.server.provider.packages</param-name>
       <param-value>com.example</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>



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.example;

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

/**
 * 
 */

/**
 * @author Santosh
 *
 */
@Path("/hello")
public class HelloWorldRS {

 @GET
 @Path("/{param}")
 public Response sayHello(@PathParam("param") String name) {
  String output = "Hello " + name + "!";
  return Response.status(200).entity(output).build();
 }

}



HelloWorldRs.java

Deploying the project to tomcat and invoking it via browser
  • In the eclipse Ide Right Click Server tab -> Add and Remove-> Select HelloWorldRS from Available Resources and Add and Finish
  • Right click on Server tab and start
  • Once the server is started without any errors upon hitting the url http://localhost:8090/HelloWorldRS/rest/hello/inetsolv you should see the output Hello inetsolv! in the browser window.


No comments:

Post a Comment