Jersey 2 CRUD example

Jersey 2 CRUD example

Jersey is very popular framework to build restful services. In our previous blog Jersey 2 Hello World Example, we came up with basic example to get start with jersey framework. In this blog we will be discussing CRUD operation with jersey which will help you to create restful services with back end data. Technologies used in this examples are :

  1. Maven as a build tool.
  2. Jersey 2.23.1
  3. JDK 1.7
  4. Tomcat 7
  5. Spring 4.1, however you can use lower versions of spring as well.
  6. Mysql as a database

This example has been implemented using Eclipse and maven plugin, used to create the basic folder structure for maven java project. Few other files have been included to implement this example. The final folder structure looks like the image below.

 

1) Jersey 2 and Spring JDBCTemplate dependencies.

Add Jersey 2, Spring JDBC and mysql dependencies into the pom.xml file.

<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>jerseyjdbctemplate</groupId>
  <artifactId>jerseyjdbctemplate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>jerseyjdbctemplate Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <!-- Jersey core Servlet 2.x implementation -->
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <version>${jersey.version}</version>
        <scope>${jersey.scope}</scope>
    </dependency>
 
    <!-- Jersey JSON Jackson (2.x) entity providers support module -->
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${jersey.version}</version>
        <scope>${jersey.scope}</scope>
    </dependency>
 
    <!-- Jersey extension module providing support for Spring 3 integration -->
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring3</artifactId>
        <version>${jersey.version}</version>
        <scope>${jersey.scope}</scope>
        <exclusions>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
 
    <!-- Spring Framework-4.x -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
 
    <!-- JDBC template -->
 
    <!-- MySql-Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>
    
    <dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>3.1.0</version>
	</dependency>
  </dependencies>
  <properties> 
      <jersey.version>2.12</jersey.version>
      <jersey.scope>compile</jersey.scope>
      <spring.version>4.1.0.RELEASE</spring.version>
      <mysql.version>5.1.32</mysql.version>
      <compileSource>1.7</compileSource>
      <maven.compiler.target>1.7</maven.compiler.target>
      <maven.compiler.source>1.7</maven.compiler.source>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <build>
    <finalName>jerseyjdbctemplate</finalName>
  </build>
</project>

For table creation, bean class and all other JDBCTemplate code, please refer and follow the steps in spring JDBCTemplate example.

2) Add below servlet mapping configuration into web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <servlet>
       <servlet-name>jersey-servlet</servlet-name>
       <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
       <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.code2succeed.rest</param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
   </servlet>
  
   <servlet-mapping>
       <servlet-name>jersey-servlet</servlet-name>
       <url-pattern>/rest/*</url-pattern>
   </servlet-mapping>
   
   <!-- loading Spring Context for registering beans with ApplicationContext -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

3) Rest service class.

Create Rest service class EmpService.java which contains code for CRUD application. Below are description of each methods.

Method NameDescription
update(Emp emp)Update Emp data(JSON) to database.
getById(int id)Returns specific Emp based on id in JSON format.
getAll()Returns all emp from Emp table in JSON format.
save(Emp emp)Insert Emp data(JSON) to database.
deleteById(int id)Delete specific Emp based on id.

package com.code2succeed.rest;

import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;

import com.code2succeed.beans.Emp;
import com.code2succeed.dao.EmpDao;

@Path("/emp")
public class EmpService {

	@Autowired
	private EmpDao empDao;
	
	@Path("/getAll")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response getAll() {
		List<Emp> emps = empDao.getAll();
		return Response.status(200).entity(emps).build();
	}
	
	@Path("/get/{id}")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response getById(@PathParam("id") int id) {
		Emp emp = empDao.getById(id); 
		return Response.status(200).entity(emp).build();
	}
	
	@Path("/save")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response save(Emp emp) {
		empDao.save(emp);
		return Response.status(200).build();
	}
	
	@Path("/update")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response update(Emp emp) {
		empDao.update(emp);
		return Response.status(200).build();
	}
	
	@Path("/delete/{id}")
	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteById(@PathParam("id") int id) {
		empDao.deleteById(id);
		return Response.status(200).build();
	}
}

4) Run the application.

To run this application, we need rest client. We are using Chrome extension ‘postman’, however you can use any other application or can write your own code to consume these services.

  1. Get all Emp.

    URL : http://localhost:8080/jerseyjdbctemplate/rest/emp/getAll

  2. Get Emp by Id.

    URL: http://localhost:8080/jerseyjdbctemplate/rest/emp/get/1

  3. Insert new Emp.

    URL: http://localhost:8080/jerseyjdbctemplate/rest/emp/save

    Input data in JSON format:

    {
        "id": 3,
        "firstName": "Sandeep",
        "lastName": "Kul"
    }

    To verify insert operation, getAll Emp data using URL: http://localhost:8080/jerseyjdbctemplate/rest/emp/getAll

    Jersey 2 CRUD Example - Save

  4. Update Emp

    URL: http://localhost:8080/jerseyjdbctemplate/rest/emp/save
    Input data in JSON format:

    {
        "id": 3,
        "firstName": "James",
        "lastName": "Anderson"
    }

    To verify update operation, getAll Emp data using URL: http://localhost:8080/jerseyjdbctemplate/rest/emp/getAllJersey 2 CRUD Example - Update

  5. Delete specific Emp

    URL: http://localhost:8080/jerseyjdbctemplate/rest/emp/delete/3.
    Data after delete operation.

Download the attached zip project.

jerseyjdbctemplate

Stay tuned for more update !!!

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *