Jersey, Gson and DataTables

With all the backend pieces in place, I’ll add a jQuery DataTable to display the data. This only requires the creation of an html table and a little bit of javascript.

First, I pull in the prerequisite assets from Bootstrap, jQuery and jQuery DataTables (Bootstrap is, of course, completely optional).

1
2
3
4
5
6
7
8
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css"/>

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"/>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

Next, I add the skeleton of a table. Note that the table has an id for easy jQuery selector identification and only contains a thead element defining the table headings – the table body will be retrieved via ajax. Because I’m using Bootstrap, I wrap the table in a container, row and col-md-8 respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>DataTable with ajax object feed</h2>
<table id="users" class="display">
<thead>
<tr>
<th>email</th>
<th>SurName</th>
<th>Given Name</th>
</tr>
</thead>
</table>
</div>
</div>
</div>

And finally, I initialize the table as a DataTable. $(‘#users’) is the jQuery selector specifying my table (object with id users). I use the ajax option to specify the source of the data source. And I use the columns option to define which object values are used in the table columns – required because I’m returning the data as an array of json objects.

1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript" class="init">
$(document).ready(function() {
$('#users').dataTable({
"ajax": "webapi/myresource/user/map",
"columns": [
{ "data": "email" },
{ "data": "surName" },
{ "data": "givenName" }
]
});
});
</script>

I’ve also added a small update to the Maven pom.xml. I’ve replaced the fictitious nitrous server name with ${env.TOMCAT_HOST}, this will use the TOMCAT_HOST environment variable as the hostname.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ git diff --staged pom.xml
diff --git a/pom.xml b/pom.xml
index c54b628..89ad12f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -37,7 +37,7 @@
</execution>
</executions>
<configuration>
- <url>http://xxxxxx-nnnnnn.use1-2.nitrousbox.com:8080/manager/text</url>
+ <url>http://${env.TOMCAT_HOST}:8080/manager/text</url>
<server>nitrous</server>
<path>/${project.build.finalName}</path>
</configuration>

You can browse the current source for jersey-gson on GitHub.

30 Sep: Custom Marshalling with Gson - part 2
12 Oct: Modal Dialog for Jersey, Gson and DataTables