Showing posts with label RESTful webservice. Show all posts
Showing posts with label RESTful webservice. Show all posts

Java RESTful example using jersey api

Before we proceed, we need almost four things up and running as part of our dev environment. Here I will be using following resources in order to design the simple RESTful service.
  1. Eclipse
  2. Tomcat
  3. Jersey library
  4. Maven
Jersey api is based on JAX-RS (JSR 311).

In nearly 4 steps we can configure and build the complete RESTful API.

  1. Open up your Eclipse IDE and create a dynamic web project and then convert it into the Maven project.
  2. Add the jersey-server dependency.
  3. Configure the jersey-server class and package entry into the web.xml file.
  4. Create the java class which will configure the url and request type and also will prepare the response.
 Maven Dependency:

Add below code snippet inside your pom.xml file. This will add the jersey-server library into the project.

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


web.xml

Add the below code snippet in your web.xml file.

<servlet>
        <servlet-name>my-jersey</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.services.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>my-jersey</servlet-name>
        <url-pattern>/restful/*</url-pattern>
    </servlet-mapping>


Java Class:

Add the below java code into your java file.

package com.services.rest;

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 FirstRestService {
   
    @GET
    @Path("/{param}")   
    public Response sendMsg(@PathParam("param") String msg){
       
        String output = "<h1>Hello! this is a : </h1>" + "<p>"+msg+"</p>";
        return Response.status(200).entity(output).build();
    }
   
    @GET
    @Path("/greeting")
    public String response(){
       
        return "<h1>Hello World</h1>";
    }

}


That's pretty much it guys, now you may go ahead and run the server and run the below url

http://localhost:8080/MyProject/restful/hello/greeting
OR
http://localhost:8080/MyProject/restful/hello/restFulWorld