Home > Uncategorized > Rest-Jersey Maven Eclipse Tutorial

Rest-Jersey Maven Eclipse Tutorial

This tutorial is going to help you get started with Jersey. In order to follow this tutorial , you must have the following things installed and integrated:-

  1.  Eclipse , maven.
  2.  Eclipse plugin for maven(m2eclipse)
  3.  Tomcat and integrate tomcat with eclipse (Optional as we can run the application with maven jetty plugin).

Create New Project
Code
Deploy/Test Jetty
Deploy/Test Tomcat


1) Create a new Maven project from Eclipse

Next select the archtype “maven-archtype-webapp” to create a simple web app project.

Add group Id , artifactId e.t.c.

Once this is done we need to create the src/main/java and src/test/java packages as they are not created when using the archtype “maven-archtype-webapp” archetype. Next update the maven project configuration by right click on the project in eclipse and under Maven, select “update project configurations”.

Next we need to add the Jersey dependencies in the pom.xml file. The dependencies are:-

  1. jersey-server
  2. jersey-client
  3. jersey-json
  4. jersey-multipart

Also we will add the jetty plugin in the pom file so that we can use the jetty to run and test the application.

The contents of the pom file are as below:-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.first.jersey.tutorial</groupId>
<artifactId>JerseyTutorial</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>JerseyTutorial Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.10</version>
</dependency>
</dependencies>
<build>
<finalName>JerseyTutorial</finalName>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>


2) Actual Code for the application

2.1) First we will create 2 model objects, Employee and Department in a new package called com.model. The java code for these two classes is shown below. (the getter and setter are omitted).

package com.model;

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

@XmlRootElement
public class Employee {

private int id;
private String firstName;
private String lastName;
private String email;
private Department dept;
}

 

package com.model;

public class Department {
private int deptId;
private String deptName;
}

2.2) Next we create a DB class in a new package (com.db). This class has some sample employees and there associated departments.

package com.db;

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

import com.model.Department;
import com.model.Employee;

public class DB {

static Map<Integer, Employee> db = new HashMap<Integer, Employee>();
 static {
 Employee emp1 = new Employee();
 emp1.setId(1);
 emp1.setFirstName("Peter");
 emp1.setLastName("Bratsh");
 Department dept1 = new Department();
 dept1.setDeptId(1111);
 dept1.setDeptName("dept1");
 emp1.setDept(dept1);

Employee emp2 = new Employee();
 emp2.setId(2);
 emp2.setFirstName("John");
 emp2.setLastName("Williams");
 Department dept2 = new Department();
 dept2.setDeptId(2222);
 dept2.setDeptName("dept2");
 emp2.setDept(dept2);

db.put(1, emp1);
 db.put(2, emp2);

}

public static Employee getEmployee(int id) {
 return db.get(id);
 }

public static List<Employee> getAllEmployees() {
 return new ArrayList<Employee>(db.values());
 }
}

2.3) Next we create the main resource class called EmployeeResource. It has 2 methods:-

getAllEmployees :- this returns all the employees.

getEmployee/id :- this will return an employee with the specific Id

package com.resource;

import java.util.List;

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

import com.db.DB;
import com.model.Employee;

@Path("/EmployeeResource")
public class EmployeeResource {

@GET
@Produces( { MediaType.APPLICATION_XML})
public List<Employee> getAllEmployees() {
return DB.getAllEmployees();
}

@GET
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("{id}")
public Employee getEmployee(@PathParam("id") int id) {
return DB.getEmployee(id);
}

}

2.4) Modify the web.xml file to have the follwoing contents:-


<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Jersey REST Service</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.resource</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>


3) Deploy and Test Using Maven Jetty Plugin

Build the application using the following command in the workspace directory. For example my project is in
F:\worspace_Jersey\JerseyTutorial> mvn clean install

Start the jetty server:-

F:\worspace_Jersey\JerseyTutorial>mvn jetty:run

Next open a browser and got to http://localhost:8080/JerseyTutorial/rest/EmployeeResource and you should see all the resources.

Next go to http://localhost:8080/JerseyTutorial/rest/EmployeeResource/1 and you will see the information for employee with id=1.

(The output xml if shown below)


4) Deploy and Test Using Tomcat
Build the application.
F:\worspace_Jersey\JerseyTutorial> mvn clean install

Next add this module to tomcat. Double click the tomcat server, click modules view , then click Add External
Web Module and give the path of the target directory, in this case it would be
F:\worspace_Jersey\JerseyTutorial\target\JerseyTurorial

Start tomcat server.Next go to http://localhost:8080/rest/EmployeeResource and you should see the below output:-

<employees>
  <employee>
    <dept>
      <deptId>1111</deptId>
      <deptName>dept1</deptName>
    </dept>
    <firstName>Peter</firstName>
    <id>1</id>
    <lastName>Bratsh</lastName>
  </employee>
  <employee>
    <dept>
      <deptId>2222</deptId>
      <deptName>dept2</deptName>
    </dept>
    <firstName>John</firstName>
    <id>2</id>
    <lastName>Williams</lastName>
  </employee>
</employees>

Go to http://localhost:8080/JerseyTutorial/rest/EmployeeResource/1.

<employee>
  <dept>
    <deptId>1111</deptId>
    <deptName>dept1</deptName>
  </dept>
  <firstName>Peter</firstName>
  <id>1</id>
  <lastName>Bratsh</lastName>
</employee>

Advertisements
Categories: Uncategorized
  1. freeclimbing
    October 16, 2013 at 10:15 am

    Worked for me with some minor changes:
    1. Remove following lines in web.xml

     

    2. Cast return value to (Employee) in DB.java:
    public static Employee getEmployee(int id) {
    return (Employee) db.get(id);
    }
    3. After your last screenshot, the link http://localhost:8080/rest/EmployeeResource is NOT working, edit it like this: http://localhost:8080/JerseyTutorial/rest/EmployeeResource
    
    Thanks!
  2. freeclimbing
    October 16, 2013 at 10:18 am

    Edit is not possible!? 😉
    The xml-Stuff fucked it up: delete the 1., 2. and last line in the web.xml, then it could be loaded and startet in the Tomcat application server 😉

  3. October 16, 2013 at 3:43 pm

    thanks for the feedback, made the necessary changes

  4. October 14, 2015 at 7:52 pm

    I had to add those two blocks in my pom.xml in order for it to work

    com.sun.jersey
    jersey-core
    1.17.1

    com.sun.jersey
    jersey-servlet
    1.17.1

    AND

    maven-compiler-plugin
    2.3.2

    1.6
    1.6

  5. October 14, 2015 at 8:00 pm

    I don’t know how to show my xml here.
    But in other word I added dependency to jersey-core et jersey-servlet.
    I also added the maven-compiler-plugin to specify the version so it can use annotation.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: