Tuesday, January 10, 2017

Java How to implement Jersey Restful Webservice

In this post, I will show you How to implement Jersey Restful Webservice.




1. Directory Structure

This is the finel webservice project structure in this article.




2. Maven dependency



<project ...>

 <repositories>
  <repository>
   <id>maven2-repository.java.net</id>
   <name>Java.net Repository for Maven</name>
   <url>http://download.java.net/maven/2/</url>
   <layout>default</layout>
  </repository>
 </repositories>

 <dependencies>

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

 </dependencies>

</project>
3. REST Service


package com.hello.test
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 AlphabetResource{

 @GET
 @Path("/{param}")
 public Response getMsg(@PathParam("param") String msg) {

  String output = "Jersey say : " + msg;

  return Response.status(200).entity(output).build();

 }

}
4. web.xml

<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>
                     com.sun.jersey.spi.container.servlet.ServletContainer
                </servlet-class>
  <init-param>
       <param-name>com.sun.jersey.config.property.packages</param-name>
       <param-value>com.hello.test</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>
5. Demo

In this tutoral, web request from "projectURL/rest/hello" will mach to class "AlphabetResource".
Any value from "projectURL/rest/hello/{param}" will match with @PathParam.

Final URL: http://localhost:8080/ITVAlphabetWS/rest/hello/helloworld.


Good luck!
Share:

0 comments:

Post a Comment

Total Pageviews