2013-05-19

Tutorial: Create a client-server application with RESTEasy and JQuery/jqPlot


With jqPlot it is possible to create nice charts and we want to use Java as backend to get the data. You can download the whole project here. We will cover the followings steps, to create a RESTEasy - JQuery/jqPlot application:



1. Requirements


What do we need:
  • Java SDK 6 or above
  • Maven
  • Eclipse Java EE Edition with Maven Plugin (m2e)
  • Tomcat or JBoss/Wildfly server

I assume that you already know how to setup this programs. If not, please take a look at relevant documentations. You can add a new server in Eclipse and run the project with 'Run As' and 'Run on Server'. If you want a Maven-only configuration, there is an interesting project on github: jszip. It's a solution to manage all the Java Script files with Maven. In this tutorial, we will add the *.js files by our own. So we also have to download the Java Script library jqPlot:


2. Create a Maven project in Eclipse and configure RESTEasy


The frist step is to add a new Maven project to Eclipse. I choose 'Create a simple project', you can just follow the wizard like in the screenshots.


Next in the pom.xml file insert behind the packaging-tag the following lines:


Create a folder WEB-INF in src/main/webapp with a file web.xml. It contains the configuration of the servlet for RESTEasy.


3. Add a REST and a POJO class


We only use two simple classes, please add these packages to the source directory src/main/java: 'de.rest.example.pojo' and 'de.rest.example.remote'. In the first package we put the VisitorCounter class. It has an array with a timestamp and a hit-value.


In the package 'de.rest.example.remote' we create the VisitorsRest class. The declared function returns the JSON data.


Now the project should look like this:


If you deploy the application to your server and open the URL (host and port may be different) http://localhost:8080/RestApp/rest/visitors/hits you should get the data:



4. Write the HTML/Java Script client


First place the extracted jqplot in a directory called 'js' under 'webapp'. Now we will create the index.html (also in 'webapp'). It contains a div-tag as placeholder for the chart. Next to JQuery und jqPlot we use a plugin dateAxisRenderer. It is in jqPlot included and allows us to render the timestamp on the x-axis.


At least we need to get the data and initialize the chart. Create a file chartController.js with the following content in 'webapp/js'.


Finally your 'webapp' directory should look like this:


That's all. Conclusion: It is really easy to create with a few lines of code a client-server application with Java as backend.