JAX-RS CRUD Application Example

JAX-RS API is used to develop RestFul web services. in Java. Most commonly used implementation is Jersey.JAX-RS specification provides annotations that are used by service programmer for annotating service methods and service class.

Commonly used annotations

  1. @Path: This annotation is used to associate a URI to a service class and methods.
  2. @GET:  This annotation is used to associate HTTP GET request to a service method.
  3. @POST: This annotation is used to associate HTTP POST request to a service method.
  4. @PUT: This annotation is used to associate HTTP PUT request to a service method.
  5. @DELETE: This annotation is used to associate HTTP DELETE request to a service method.
  6. @Produces:This annotation is used to specify the representation of a resource which is produced by a method.
  7. @Consumes: This annotation is used to specify the representation of a resource which is consumed by a method.

Required Steps

  • Create a web application and add jars files of Jersey to the WEB-INF/lib.
  • Define entity classes which are to be exposed as resources and if XML representation is generated or consumed by the service then use JAXB annotation in the entity class and its jars.
  • Define service class and associate a URI to it using @Path annotation and define service methods.
  • In web.xml add a servlet entry for the org.glassfish.jersey.servlet.ServletContainer and provide service class location by initialization parameters to this servlet and define your service class package.

Employee.java

package com.startwithjava.beans;

import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlElement;  
import javax.xml.bind.annotation.XmlRootElement;  
  
@XmlRootElement  
public class Employee {  
    private int id;  
    private String name;  
    private float salary;  
  
public Employee() {}  
public Employee(int id, String name, float salary) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.salary = salary;  
}  
@XmlAttribute  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
@XmlElement  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
@XmlElement  
public float getSalary() {  
    return salary;  
}  
public void setSalary(float salary) {  
    this.salary = salary;  
}  
  
}  

EmployeeController.java

package com.startwithjava.rest;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
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.MediaType;
import javax.ws.rs.core.Response;

import com.startwithjava.beans.Employee;
import com.startwithjava.dao.GenericDao;
import com.google.gson.Gson;
@Path("/employee/")  
public class EmployeeController {  
 @GET  
 @Path("/all/")
 @Produces(MediaType.APPLICATION_JSON)
  public String getAllEmployees(){
	 GenericDao dao = new GenericDao();
	 Gson gson = new Gson();
	 List<Employee> list = new ArrayList<Employee>();
	 ResultSet rs = dao.get("employee", null);
	 if(rs!=null){
		  try {
			while(rs.next()){
				 Employee e = new Employee();
				 e.setId(rs.getInt("id")); 
				 e.setName(rs.getString("name")); 
				 e.setSalary(rs.getFloat("salary"));
				 list.add(e);
			  }
		} catch (SQLException ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}
	  }
	  return gson.toJson(list);
  }	
  @GET  
  @Path("/{id}")
  @Produces(MediaType.APPLICATION_JSON)
  public String getEmployeeById(@PathParam("id") int id) {  
	  Gson gson = new Gson();
	  GenericDao dao = new GenericDao();
	  Employee e = new Employee();
	  HashMap<String, Object> map = new HashMap<String, Object>();
	  map.put("id", id);
	  ResultSet rs = dao.get("employee", map);
	  if(rs!=null){
		  try {
			while(rs.next()){
				 e.setId(rs.getInt("id")); 
				 e.setName(rs.getString("name")); 
				 e.setSalary(rs.getFloat("salary"));
			  }
		} catch (SQLException ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}
	  }
	  return gson.toJson(e);
	  //return e;	  
  }  
  @GET  
  @Path("/{id}")
  @Produces(MediaType.APPLICATION_XML)
  public Employee getEmployeeByIdInXML(@PathParam("id") int id) {  
	  Gson gson = new Gson();
	  GenericDao dao = new GenericDao();
	  Employee e = new Employee();
	  HashMap<String, Object> map = new HashMap<String, Object>();
	  map.put("id", id);
	  ResultSet rs = dao.get("employee", map);
	  if(rs!=null){
		  try {
			while(rs.next()){
				 e.setId(rs.getInt("id")); 
				 e.setName(rs.getString("name")); 
				 e.setSalary(rs.getFloat("salary"));
			  }
		} catch (SQLException ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}
	  }
	  //return gson.toJson(e);
	  return e;	  
  }  
  @POST
  @Path("/add")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({ MediaType.APPLICATION_JSON})
  public Response addEmployee(String empJson) {
	 Gson gson = new Gson();
	 Employee emp = gson.fromJson(empJson, Employee.class);
	 GenericDao dao = new GenericDao(); 
	 Response r = null;
	 HashMap<String, Object> map = new HashMap<String, Object>();
	 map.put("id", emp.getId());
	 map.put("name", emp.getName());
	 map.put("salary",emp.getSalary());
	 int status=0;
	try {
		dao.insert("employee", map);
		r =  Response.status(Response.Status.OK).entity("Successfully Created").build();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		r= Response.status(Response.Status.BAD_REQUEST).entity("Unable to add new Employee").build();
	}
	 return r;
  } 
  @DELETE
  @Path("/{id}")
  @Produces({ MediaType.APPLICATION_JSON})
  public Response deleteEmployee(@PathParam("id") int id){ 
	Response r = null;
	 GenericDao dao = new GenericDao(); 
	 if(id!=0){
		 HashMap<String, Object> map = new HashMap<String, Object>();
		 map.put("id", id);
		 int staus = dao.delete("employee", map);
		 r =  Response.status(Response.Status.OK).entity("Successfully deleted").build();
		 
	 }else{
		 
		 r= Response.status(Response.Status.BAD_REQUEST).entity("Please provide employee id").build();
	 }
	 return r;
  }
  @POST
  @Path("/update")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({ MediaType.APPLICATION_JSON})
  public Response updateEmployee(String empJson) {
	  System.out.println("::::::::empJson="+empJson);
	 Gson gson = new Gson();
	 Employee emp = gson.fromJson(empJson, Employee.class);
	 GenericDao dao = new GenericDao(); 
	 Response r = null;
	 HashMap<String, Object> map = new HashMap<String, Object>();
	 HashMap<String, Object> cond = new HashMap<String, Object>();
	 map.put("name", emp.getName());
	 map.put("salary",emp.getSalary());
	 cond.put("id", emp.getId());
	 int status=0;
	try {
		dao.update("employee", map,cond);
		r =  Response.status(Response.Status.OK).entity("Successfully updated").build();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		r= Response.status(Response.Status.BAD_REQUEST).entity("Unable to update Employee").build();
	}
	 return r;
  }  
 
} 

index.jsp

 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>RestFul Web Sevices by StartWithJava</title>

<style>

</style>
</head>
<body>
<h1>RestFul CRUD Application</h1>
<a href="javascript:void(0);" onclick="add();">Add Employee</a>
<br/><br/>
<table id="empData" width="750px" cellpadding="1" border="1">
</table>
<script>
jQuery(document).ready(function(){
    $.ajax({
        url: "http://localhost:9898/JAX-RS/rest/employee/all",
        type:"GET",
        success: function(data) {
            
        if(data!=null){
                var html = "<tr><td>ID</td><th>Name</td><td>Salary</td><td>Actions</td></tr>";
                $.each(data, function(i, employee) {
                  //use obj.id and obj.name here, for example:
                 // alert(employee.name);
                   html += "<tr id='row_"+employee.id+"'><td>"+employee.id+"</td><td>"+employee.name+"</td><td>"+employee.salary+"</td>";
                   html += "<td><a href='javascript:void(0);' onclick='editEmployee("+employee.id+")'>Edit</a>|";
                   html += "<a href='javascript:void(0);' onclick='deleteEmployee("+employee.id+")'>Delete</a></td>";
                 
                });
                $("#empData").append(html);
        }    
            
        },
        error: function(data) {}
    });
    $("#frmAdd").submit(function(){
        $.ajax({
            url: "http://localhost:9898/JAX-RS/rest/employee/add",
            type:"POST",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data:formToJSON(),
            statusCode : {
                200 : function(jqXHR) {
                     var html="";
                       html += "<tr><td>"+$('#id').val()+"</td><td>"+$('#name').val()+"</td><td>"+$('#salary').val()+"</td>";
                       html += "<td><a href='javascript:void(0);' onclick='editEmployee("+$('#id').val()+")'>Edit</a>|";
                       html += "<a href='javascript:void(0);' onclick='deleteEmployee("+$('#id').val()+")'>Delete</a></td>";
                      $("#empData").append(html);
                      $("#id").val("");
                      $("#name").val("");
                      $("#salary").val("");

                },
             400:function(jqXHR){
                 
                  alert("Please provide valid data");
             }

            },
        });
        return false;
    });    
    $("#frmEdit").submit(function(){
        $.ajax({
            url: "http://localhost:9898/JAX-RS/rest/employee/update",
            type:"POST",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data:formToJSON2(),
            statusCode : {
                200 : function(jqXHR) {
                     var html="";
                       html += "<tr id='row_"+$('#id2').val()+"'><td>"+$('#id2').val()+"</td><td>"+$('#name2').val()+"</td><td>"+$('#salary2').val()+"</td>";
                       html += "<td><a href='javascript:void(0);' onclick='editEmployee("+$('#id').val()+")'>Edit</a>|";
                       html += "<a href='javascript:void(0);' onclick='deleteEmployee("+$('#id').val()+")'>Delete</a></td>";
                       $("#row_"+$('#id2').val()).replaceWith(html);
                      // $("#empData").append(html);
                       alert("Profile Updated successfully");
                      $("#id").val("");
                      $("#name").val("");
                      $("#salary").val("");
                       $("#frmEdit").hide(); 

                },
             400:function(jqXHR){
                 
                  alert("Please provide valid data");
             }

            },
        });
        return false;
    });    
});
 function formToJSON() {
    var str= JSON.stringify({
        "id": $('#id').val(),
        "name": $('#name').val(),
        "salary": $('#salary').val()
        });
    return str;
}
 function formToJSON2() {
        var str= JSON.stringify({
            "id": $('#id2').val(),
            "name": $('#name2').val(),
            "salary": $('#salary2').val()
            });
        return str;
    }
 function deleteEmployee(id){
    $.ajax({
            url: "http://localhost:9898/JAX-RS/rest/employee/"+id,
            type:"DELETE",
            statusCode : {
                200 : function(jqXHR) {
                             $("#row_"+id).remove();    
                    },
                 400:function(jqXHR){
                      alert("Please provide valid data");
                 }
            }
    }); 
 }
 function editEmployee(id){
     $.ajax({
            url: "http://localhost:9898/JAX-RS/rest/employee/"+id,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function(data) {
            if(data){
                    $("#frmEdit #id2").val(data.id);
                    $("#frmEdit #name2").val(data.name);
                    $("#frmEdit #salary2").val(data.salary);
                    $("#frmAdd").hide();
                    $("#frmEdit").show();
            }    
                
            },
            error: function(data) {}
        }); 
 }
 function add(){
     $("#frmAdd").show();
     $("#frmEdit").hide(); 
     
 }
</script>
<br/><br/><br/><br/>
<form action="" id="frmAdd" method="post">
<h2>Add Employee</h2>
<table width="750px">
<tr>
    <td>Id</td>
     <td><input type="text" name="id" id="id"></td>
</tr>
<tr>
    <td>Name</td>
     <td><input type="text" name="name" id="name"></td>
</tr>
<tr>
    <td>Salary</td>
     <td><input type="text" name="salary" id="salary"></td>
</tr>
<tr>
    <td></td>
     <td><input type="submit" name="add" value="Add Employee"></td>
</tr>
</table>
</form>
<form action="" id="frmEdit" method="post" style="display:none;">
<h2>Update Employee</h2>
<table width="750px">
<tr>
    <td>Id</td>
     <td><input type="text" name="id" id="id2"></td>
</tr>
<tr>
    <td>Name</td>
     <td><input type="text" name="name" id="name2"></td>
</tr>
<tr>
    <td>Salary</td>
     <td><input type="text" name="salary" id="salary2"></td>
</tr>
<tr>
    <td></td>
     <td><input type="submit" name="update" value="Update Employee"></td>
</tr>
</table>
</form>
</body>
</html>

web.xml

<?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" 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">  
     <servlet>  
        <servlet-name>Jersey REST Service</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.startwithjava.rest</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>   

restful web service

Download JAX-RS Project

Leave a Reply