Build a RESTful application using jqGrid

This tutorial shows how you can build up an Enterprise application using jQuery and jqGrid plugin on the client side and REST Web services deployed on WildFly application server.

Let’s start building the server side at first. Our SimpleRESTService contains two methods only: getPersonList which retrieves a list of Person Entity using a JPA Query and controller method that is invoked for create/delete/update operations.

@Stateless
@Path("/service")
public class SimpleRESTService {

    @PersistenceContext
    EntityManager em;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getPersonList()

    {

        Query query = em.createQuery("FROM Person");
        List<Person> customerList = query.getResultList();
        return customerList;
    }

    @POST
    @Path("/controller")
    @Consumes(MediaType.APPLICATION_JSON)
    public void controller(String message) {
        JsonReader reader = Json.createReader(new StringReader(message));
        JsonObject obj = reader.readObject();

        String oper = obj.getString("oper");
        switch (oper) {
        case "add":
            addElement(obj);
            break;
        case "del":
            deleteElement(obj);
            break;
        default:
            editElement(obj);
        }
    }

    private void editElement(JsonObject obj) {
        String id = obj.getString("id");
        String name = obj.getString("name");
        String surname = obj.getString("surname");
        String address = obj.getString("address");

        Person person = em.find(Person.class, new Long(id));

        person.setName(name);
        person.setSurname(surname);
        person.setAddress(address);
        em.merge(person);

    }

    private void addElement(JsonObject obj) {

        Person person = new Person();
        person.setName(obj.getString("name"));
        person.setSurname(obj.getString("surname"));
        person.setAddress(obj.getString("address"));

        em.persist(person);
        System.out.println("Saved " + person);

    }

    private void deleteElement(JsonObject obj) {

        String id = obj.getString("id");
        Query query = em.createQuery("delete FROM Person where id = :id");
        query.setParameter("id", id);
        query.executeUpdate();
        System.out.println("Deleted " + obj);

    }
}

The Entity class is quite simple, containing two fields and one auto-generated id field

@Entity
public class Person {
    public Person() {     }
 
    public Person(String name, String surname) {
        this.name = name;
        this.surname = surname;
    }
 
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String surname;
     
    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;
    }
}

Our REST application needs as well a JAX-RS Activator class which enables REST Services setting as base path “rest”:

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}

Our server application is completed. You need the configuration file for JPA Persistence. To keep it simple, we will be using the default ExampleDS which ships with the application server. This file named persistence.xml needs to be included in the resources/META-INF folder of your project.

<persistence version="2.0"
   xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
   <persistence-unit name="primary">
      <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
      <properties>
         <!-- Properties for Hibernate -->
         <property name="hibernate.hbm2ddl.auto" value="create-drop" />
         <property name="hibernate.show_sql" value="false" />
      </properties>
   </persistence-unit>
</persistence>

Finally, although not mandatory, we will include as well an import.sql file in the resources folder of your Maven application. This will create some initial data that can be displayed:

insert into person (id,name,surname,address) values (0,'freddie','smith','Euston Road')
insert into person (id,name,surname,address) values (1,'joe ','francis','Park Lane')
insert into person (id,name,surname,address) values (2,'paul','stephens','Piccadilly avenue')

Now on the client side. We will be using jQuery and jqGrid. jqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating tabular data on the web. Since the grid is a client-side solution loading data dynamically through Ajax callbacks, it can be integrated with our server-side REST Service.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jqGrid Tutorial</title>

<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/ui.jqgrid.css" />
 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script src="http://trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery.extend(
        jQuery.jgrid.edit, {
            ajaxEditOptions: { contentType: "application/json" },
            recreateForm: true,
            serializeEditData: function(postData) {
                return JSON.stringify(postData);
            },
            afterSubmit: function (response, postdata) {
                var res = jQuery.parseJSON(response.responseText);
                return [true, "", res.d];
            }
        }
    );

$(document)
.ready(
        function() {
            $("#list")
                    .jqGrid(
                            {
                                url : 'http://localhost:8080/rest-angular/rest/service',
                                datatype : 'json',
                                mtype : 'GET',
                                colNames : [ 'name', 'surname',
                                        'address'],
                                colModel : [ {
                                    name : 'name',
                                    index : 'name',
                                    width : 150,
                                    editable : true
                                }, {
                                    name : 'surname',
                                    index : 'surname',
                                    width : 150,
                                    editable : true
                                }, {
                                    name : 'address',
                                    index : 'address',
                                    width : 200,
                                    editable : true
                                } ],
                                pager : '#pager',
                                rowNum : 10,
                                rowList : [ 10, 20, 30 ],
                                sortname : 'invid',
                                sortorder : 'desc',
                                viewrecords : true,
                                gridview : true,
                                caption : 'Data Report',
                                jsonReader : {
                                    repeatitems : false,
                                },
                                editurl : "http://localhost:8080/rest-angular/rest/service/controller",
                                datatype : 'json'
                            });
            jQuery("#list").jqGrid('navGrid', '#pager', {
                edit : true,
                add : true,
                del : true,
                search : true
            });
        });
   
</script>
</head>
<body>
    <table id="list">
        <tr>
            <td />
        </tr>
    </table>
    <div id="pager"></div>
</body>
</html>

Basically, an instance of jqGrid is a javascript object, with properties, events and methods. Properties may be strings, numbers, arrays, boolean values or even other objects.
Within this example, data is retrieved from url : ‘http://localhost:8080/rest-angular/rest/service’ which returns data in JSON format. The colNames and colModel define respectively the header contained in the grid and the model which has been returned from JSON. Next, we have defined a set of properties that eventually determine how the items are paged, sorterd and displayed. Finally we have enabled all possible CRUD operations on the grid by setting:

jQuery("#list").jqGrid('navGrid', '#pager', {
                edit : true,
                add : true,
                del : true,
                search : true
});

Each time that a create/delete/update operation is POSTed to the server, it sent in this JSON format:
{“name”:”joe “,”surname”:”dalton”,”address”:”Park Lane”,”oper”:”edit”,”id”:”2″}
This kind of format works well with a controller on the server side that can handle multiple type of operations with a single REST URL. Here’s the resulting grid in action:

angularjs jqgrid

Adding a new Person:

Editing a Person:

angularjs jqgrid

That’s all! In the next tutorial we will explore some more type of interactions between jqGrid plugin and Java server side applications. Stay tuned!

Found the article helpful? if so please follow us on Socials