Consuming a RESTful service with Ajax

In this tutorial you will consume a RESTful service (that we deploy on WildFly application server) with a simple Ajax Client.

Let’s start from the REST Endpoint:

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;
 
 
@Path("persons")
@ApplicationScoped
@Produces("application/json")
@Consumes("application/json")
public class DemoEndpoint {
 
    @Inject DemoRepository demoRepository;
 
    @GET
    public List<Person> getAll() {
        return demoRepository.findAll();
    }
 
    @POST
    public Response create(Person p) {
        demoRepository.createPerson(p);
        return Response.status(201).build();
 
    }
 
    @PUT
    public Response update(Person p) {
        demoRepository.updatePerson(p);
        return Response.status(204).build();
    }
    @DELETE
    public Response delete(@QueryParam("id") Integer id) {
        demoRepository.deletePerson(id);
        return Response.status(204).build();
    }
 
}

As you can see, this REST Service contains CRUD methods to perform the basic operations on the Person class.

The Repository class uses a plain memory structure to store your objects:

package com.packt.quarkus.chapter4;

import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;


@ApplicationScoped
public class DemoRepository {

    List<Person> list = new ArrayList();
    int counter;

    public int getNextCustomerId() {
        return counter++;
    }

    public List<Person> findAll() {
        return list;
    }

    public Person findPersonById(Integer id) {
        for (Person c: list) {
            if (c.getId().equals(id))  {
                return c;
            }
        }
        throw new RuntimeException("Person not found!");
    }

    public void updatePerson(Person person) {
        Person personToUpdate = findPersonById(person.getId());
        personToUpdate.setName(person.getName());
        personToUpdate.setSurname(person.getSurname());
    }

    public void createPerson(Person person) {
        person.setId(getNextCustomerId());
        findAll().add(person);
    }

    public void deletePerson(Integer id) {
        Person c = findPersonById(id);
        findAll().remove(c);
    }
}

Then, here is the POJO Class named Person:

public class Person {
    private Integer id;
    private String name;
    private String surname;

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", surname='" + surname + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }
}

Finally, include a REST Activator which activates REST Services under the URI “/rest”:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
   /* class body intentionally left blank */
}

 Done with the server side. Now let’s add an index.hml page to display the List of Person in an HTML Table:

<html>
<head>
    <!-- little bit of css to beutify the table -->
    <link rel="stylesheet" type="text/css" href="stylesheet.css" media="screen" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>


    <script type="text/javascript">

$(document).ready(function () {
    $.getJSON("http://localhost:8080/rest/app/persons",
    function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + json[i].id + "</td>");
            tr.append("<td>" + json[i].name + "</td>");
            tr.append("<td>" + json[i].surname + "</td>");
            $('table').append(tr);
        }
    });
});
</script>
</head>

<body>
<div align="left" style="margin-top: 10%;">
    <fieldset style="border: none;">
        <legend><strong>Users List</strong></legend>

        <!-- table to show data -->
        <table class="greyGridTable">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Surname</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </fieldset>
</div>

</body>
</html>

Some CSS style has been included in the file stylesheet.css:

table.greyGridTable {
  border: 2px solid #FFFFFF;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}
table.greyGridTable td, table.greyGridTable th {
  border: 1px solid #FFFFFF;
  padding: 3px 4px;
}
table.greyGridTable tbody td {
  font-size: 13px;
}
table.greyGridTable td:nth-child(even) {
  background: #EBEBEB;
}
table.greyGridTable thead {
  background: #FFFFFF;
  border-bottom: 4px solid #333333;
}
table.greyGridTable thead th {
  font-size: 15px;
  font-weight: bold;
  color: #333333;
  text-align: center;
  border-left: 2px solid #333333;
}
table.greyGridTable thead th:first-child {
  border-left: none;
}

table.greyGridTable tfoot td {
  font-size: 14px;
}

That’s all. Make sure the following dependencies are included in your pom.xml file:

<dependency>
      <groupId>org.jboss.spec.javax.ws.rs</groupId>
      <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
      <scope>provided</scope>
</dependency>
<dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
      <scope>provided</scope>
</dependency>

Deploy the application with

$ mvn package wildfly:deploy

Now we can try adding some data with cURL:

$ curl -d '{"name":"john", "surname":"black"}' -H "Content-Type: application/json" -X POST http://127.0.0.1:8080/persons
$ curl -d '{"name":"victor", "surname":"frankenstein"}' -H "Content-Type: application/json" -X POST http://127.0.0.1:8080/persons

Let’s surf to localhost:8080 to check that Data is listed in our table:

quarkus tutorial json ajax

Great. We could see how easily JSON data can be parsed with some help from jQuery and Ajax!