Getting started with Restful web service in java using jersey

Creating Restful web services in java is not a difficult task. You just use some annotation to expose you methods as web service end points. All annotations those turn your method into web services are in javax.ws.rs package. To host you web service, you can use tomcat or any web server. One thing you need to do is, configure the jersey ServletContainer servlet in web.xml for the particular url pattern.

See the following example depicting the calculator service.

package pack;

import java.net.URI;
import java.net.URISyntaxException;

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

@Path("/cal")
public class CalculatorResource {
    @GET
    @Produces("text/plain")
    public String getDate() {
        return "Server date:" + new java.util.Date();
    }
    @GET
    @Path("/add/{x}/{y}")
    @Produces("application/xml")
    public String add(@PathParam("x")int x,@PathParam("y")int y){
        return "<result>\n" +
                "     <first-value>"+x+"</first-value>\n" +
                "     <second-value>"+y+"</second-value>\n" +
                "     <sum>"+(x+y)+"</sum>\n" +
                "</result>";
    }
    @POST
    @Path("/add")
    @Produces("application/xml")
    public String add2(@PathParam("x")int x,@PathParam("y")int y){
        return "<result>\n" +
                "     <first-value>"+x+"</first-value>\n" +
                "     <second-value>"+y+"</second-value>\n" +
                "     <sum>"+(x+y)+"</sum>\n" +
                "</result>";
    }
}

jersey ServletContainer servlet config in web.xml

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

Popular Posts