RESTful Web Services with Jersey JAX-RS on Tomcat 7

In this tutorial, We are going to show you how to develop RESTful services with Jersey and how to deploy them on a Tomcat server. The RESTful approach of developing web services is constantly gaining more and more attention and seems to be pushing SOAP into deprecation.

Now the follow the following steps to build the JAX-RS web service with Jersey and deploy to Tomcat7.
Technologies and Tools used in this article:
  • Jersey 2.0
  • JDK 1.7
  • Tomcat 7.0
  • STS 2.7

Step 1) Create Dynamic Web Application "RESTWebApp".


Step 2) Create web.xml (deployment descriptor) under WebRoot\WEB-INF\ .

Step 3) Open web.xml file and add below code just above :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>RESTWebApp</display-name>
 <servlet>
  <servlet-name>jersey-serlvet</servlet-name>
  <servlet-class>
         com.sun.jersey.spi.container.servlet.ServletContainer
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>jersey-serlvet</servlet-name>
  <url-pattern>/doj/*</url-pattern>
 </servlet-mapping>
</web-app>

Step 4) Adding two jars file You can download from here: asm-3.3.1.jar, jersey-bundle-1.14.jar

Step 5) Creating Employee bean class
Employee.java
package com.dineshonjava.ws.rest.bean;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh Rajput
 *
 */

@XmlRootElement(name = "employee")
public class Employee {
 private String employeeId;
    private String employeeName;
    private String jobType;
    private String address;
    private Long salary;
    
    @XmlElement
    public String getEmployeeId() {
        return employeeId;
    }
    
    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }
    
    @XmlElement
    public String getEmployeeName() {
        return employeeName;
    }
    
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    @XmlElement
 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 @XmlElement
 public Long getSalary() {
  return salary;
 }

 public void setSalary(Long salary) {
  this.salary = salary;
 }

 @XmlElement
 public String getJobType() {
  return jobType;
 }

 public void setJobType(String jobType) {
  this.jobType = jobType;
 }
       
}

Step 6) Create WebController.java file
package com.dineshonjava.ws.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import com.dineshonjava.ws.rest.bean.Employee;

/**
 * @author Dinesh Rajput
 *
 */

@Path("/webservice")
public class WebController {
 
  private static Map<String, Employee> employees = new HashMap<String, Employee>();
     
     static {
         
         Employee employee1 = new Employee();
         employee1.setEmployeeId("11111");
         employee1.setEmployeeName("Dineh Rajput");
         employee1.setJobType("Sr.Software Engineer");
         employee1.setSalary(70000l);
         employee1.setAddress("Noida");
         employees.put(employee1.getEmployeeId(), employee1);
         
         Employee employee2 = new Employee();
         employee2.setEmployeeId("22222");
         employee2.setEmployeeName("Abhishek");
         employee2.setJobType("Marketing");
         employee2.setSalary(50000l);
         employee2.setAddress("New Delhi");
         employees.put(employee2.getEmployeeId(), employee2);
         
     }

     @GET
     @Path("/hello")
     @Produces("text/plain")
     public String hello(){
         return "Hello World!!! dineshonjava";    
     }
     
     @GET
     @Path("/message/{message}")
     @Produces("text/plain")
     public String showMsg(@PathParam("message") String message){
         return message;    
     }
     
     @GET
     @Path("/employees")
     @Produces("application/xml")
     public List<Employee> listEmployees(){
         return new ArrayList<Employee>(employees.values());
     }
     
     @GET
     @Path("/employee/{employeeid}")
     @Produces("application/xml")
     public Employee getEmployee(@PathParam("employeeid")String employeeId){
         return employees.get(employeeId);        
     }
     
     @GET
     @Path("/json/employees/")
     @Produces("application/json")
     public List<Employee> listEmployeesJSON(){
         return new ArrayList<Employee>(employees.values());
     }

     @GET
     @Path("/json/employee/{employeeid}")
     @Produces("application/json")
     public Employee getEmployeeJSON(@PathParam("employeeid")String employeeId){
         return employees.get(employeeId);        
     }
  
}
Step 7) Deploy project "RESTWebApp" on Tomcat7. Web project should be deployed without any exception.

Step 8) If every thing fine then test it now following link.
http://localhost:8181/sdnext/doj/webservice/hello


http://localhost:8181/sdnext/doj/webservice/message/Welcome%20to%20DineshOnJava.com


http://localhost:8181/sdnext/doj/webservice/employees


http://localhost:8181/sdnext/doj/webservice/employee/11111


http://localhost:8181/sdnext/doj/webservice/json/employees

 http://localhost:8181/sdnext/doj/webservice/json/employee/11111


Download Source Code + Libs
RESTWebApp.zip


References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 



<<Previous <<   || Index ||   >>Next >>


12 comments:

  1. HI, Dinesh, in this example, you didnot show @post annotation, i.e, how to post an employee . you explained only how to get the data.Please Explain how to post also.

    ReplyDelete
  2. Thanks Dinesh!. Excellent Tutorial.

    ReplyDelete
  3. Hi Dinesh ...
    You have mentioned that you have used jersey2.0 but actually you used jersey 1.18

    ReplyDelete
  4. This is not Jersey 2.X its Jersey 1.X

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. I use 32-bit:
    tomcat 7.0.50, jdk 1.7.0_45, eclipse Kepler 4.3

    When I run it on Eclipse there is an exception:

    SEVERE: The ResourceConfig instance does not contain any root resource classes.
    lut 03, 2014 1:26:12 PM org.apache.catalina.core.ApplicationContext log
    SEVERE: StandardWrapper.Throwable
    com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
    at com.sun.jersey.server.impl.application.RootResourceUriRules.(RootResourceUriRules.java:99)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1300)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:163)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:769)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:765)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760)
    at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
    ...

    lut 03, 2014 1:26:12 PM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /RESTWebApp threw load() exception
    com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
    at com.sun.jersey.server.impl.application.RootResourceUriRules.(RootResourceUriRules.java:99)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1300)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:163)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:769)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:765)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760)
    at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
    ...

    lut 03, 2014 1:26:12 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-apr-8080"]
    lut 03, 2014 1:26:12 PM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-apr-8009"]
    lut 03, 2014 1:26:12 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 2727 ms

    ReplyDelete
  7. can you explain sdnext in your URL?

    ReplyDelete
  8. for sdnext - check dynamic web project properties -> web project settings -> context root

    ReplyDelete
  9. Neat example, Nicely explained and more importantly it works. Only thing you may need to change once you export to your IDE (most likely eclipse) is your JRE setting and you may be add to JaxB jar to make your Model class error free.

    ReplyDelete
    Replies
    1. Thanks Goutam for nice comments as well as your suggestion.

      Happy learning with us!!!!

      Delete