Srikanth Technologies

REST API for Employees with jQuery Client

In this blog, I create a Restful service to provide details of employees from EMPLOYEES table in Oracle Database. It supports the following two URLs. I assume Glassfish is running at port number 8888 and project name is hrservice.
 

Creating RESTful Service

I use NetBeans 8.0.2 and GlassFish 4.1 for this blog. Take the following steps to create a web project and Restful service.

  1. Start NetBeans and create a new web project with name hrservice
  2. Add ojdbc6.jar (Oracle JDBC Driver) to libraries node of the project as we use Oracle Database
  3. Select hrservice project in Projects tab. Use right click to bring popup menu and select New->Other. Select Web Services in Category and RESTful Web Servies from Patterns in File Types
  4. Select Simple Root Resource in Select Pattern step
  5. Enter the following details in the next screen as shown in the screenshot

  6. Netbeans creates two files - ApplicationConfig.java and EmployeesResource.java
  7. ApplicationConfig.java is used to route urls to classes. It contains @ApplicationPath annotation to specify path that is associated with RESTful services. It also registers classes that are to be considered for routing

    package rest;
    
    import java.util.Set;
    import javax.ws.rs.core.Application;
    @javax.ws.rs.ApplicationPath("webresources")
    public class ApplicationConfig extends Application {
        @Override
        public Set<Class<?>> getClasses() {
            Set<Class<?>> resources = new java.util.HashSet<>();
            addRestResourceClasses(resources);
            return resources;
        }
        private void addRestResourceClasses(Set<Class<?>> resources) {
            resources.add(rest.EmployeesResource.class);
        }
    }
    
  8. Modify EmployeesResource.java as follows. @Path annotation is used to map URL pattern to Restful service. @Path annotation can be given for a method to further add path parameters.  @PathParam is used to copy path parameter to method parameter.

    package rest;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.sql.rowset.CachedRowSet;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.WebApplicationException;
    import javax.ws.rs.core.Response;
    import oracle.jdbc.rowset.OracleCachedRowSet;
    
    @Path("employees")
    public class EmployeesResource {
        // use this method when URL is /employees
        @GET
        @Produces("application/json")
        public List<Employee> getEmployees()  {
            try {     
                CachedRowSet crs = new OracleCachedRowSet();
                crs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
                crs.setUsername("hr");
                crs.setPassword("hr");
                crs.setCommand("select * from employees");
                crs.execute();
                ArrayList<Employee> emps = new ArrayList<>();
                while(crs.next()) {
                    Employee  e  = new Employee();
                    e.setName( crs.getString("first_name"));
                    e.setSalary( crs.getInt("salary"));
                    emps.add(e);
                }
                return emps;
          }
          catch(Exception ex) {
              throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
          }
        } // getEmployees()
        
        @Path("{id}")   // use this method when URL contains id also (employees/id) 
        @GET
        @Produces("application/json")
        public Employee getEmployee( @PathParam("id") int id)  {
          try {     
                CachedRowSet crs = new OracleCachedRowSet();
                crs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
                crs.setUsername("hr");
                crs.setPassword("hr");
                crs.setCommand("select * from employees where employee_id = ?");
                crs.setInt(1,id);
                crs.execute();
                if (crs.next()) {
                    Employee  e  = new Employee();
                    e.setName( crs.getString("first_name"));
                    e.setSalary( crs.getInt("salary"));
                    return e;
                }
                else
                    throw new WebApplicationException(Response.Status.NOT_FOUND); //employee not found so send 404 to client 
          }
          catch(SQLException ex) {
             throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); //Some exception on server, so send 500 to client
          }
        } // getEmployee()
    }
            

Creating jQuery Client

We create two different HTML pages. First page is to list all employees received from service. It makes a request with url /employees.

Both the pages use jQuery 2.x. So make sure jQuery is placed in webpages folder of your project.

listemployees.html

<!DOCTYPE html>
<html>
    <head>
        <title>List of Employees</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="jquery-2.1.4.js" type="text/javascript"></script>
        <script>
            $(function () {
                $.ajax("http://localhost:8888/restdemo/rest/employees",
                   {
                       success: showResult,  // call on success
                       error: showError      // call on error 
                   }
               );
            }
            );
            // parameter is an array of Javascript objects  
            function showResult(employees) {
                var output = "";
                $.each(employees,
                    function (idx, emp) {
                        output += "<li>" + emp.name + "," + emp.salary + "</li>";
                    }
                );
                $("#details").html(output);
            }
            
            function showError(xhr) {
                alert("Sorry! Error on server!");
            }
        </script>
    </head>
    <body>
        <h2>List of Employees</h2>
        <ul id="details">
        </ul>
    </body>
</html>

empclient.html

This page takes employee id from user and displays details of employee. If employee is not found as server sends response status 404, we display error message in client. Similarly when an error occurs on server, we get response status 500 and we display error message in client.

<!DOCTYPE html>
<html>
    <head>
        <title>Employee Client</title>
        <script src="jquery-2.1.4.js" type="text/javascript"></script>
        <script>
            function getDetails() {
                $.ajax("http://localhost:8888/restdemo/rest/employees/" + $("#empid").val(),
                        {
                            success: showResult,  // call on success
                            error: showError      // call on error
                        }
                );
            }

            function showResult(emp) {
                $("#details").html(emp.name + "," + emp.salary);
            }

            function showError(xhr) {
                if (xhr.status === 404) 
                    $("#details").html("Employee not found!");
                else
                    if (xhr.status === 500)
                        $("#details").html("Server Error!");
            }


        </script>
    </head>
    <body>
        <h2>Employee Information </h2>
        Employee Id : <input type="text" id="empid" />
        <p/>
        <button onclick="getDetails()">Get Details</button>
        <p/>
        <h2 id="details"></h2>


    </body>
</html>

Deploy the project. Run listemployees.html to get the list of employees displayed as bullets. Then test empclient.html by providing a valid employee id and also an invalid employee id.