Subscribe via RSS Feed

Developing Java REST web applications with Backbone.js

April 26, 2013 3 Comments


Recently in our J2ee based web application development, we had explored Javascript MVC frameworks to develop structured User Interface Development. Within javascript frameworks, we have found sufficient documentation for Backbone.js to develop sample Proof of Concept with J2ee based Application Back End.

We are writing post as we have not found a full-fledged Java based web application with backbone.js as UI development tool in Web.  While working on the POC, we have changed codes in backbone.js section.

We have learned the where-about from Backbone.js Wine Cellar Tutorial — Part 2: CRUD by Christophe Coenraets and used his sample POC to develop a J2ee web application with Backbone.js as web tier development framework. The main Application credit goes to him.

We have uploaded the Sample Application in GitHub (here is the Link).

Now below is the basic understanding for the overall project -

The J2ee Project is based on java jersey REST based framework. The database schema is attached in the project source code, which is named - cellar.sql

Development  environment -

1> Database – MySql

2> Rest based Web Services Development –  Java Jersey.

3> UI Development – Backbone.js

Deployment Environment -

1> Apache Tomcat 7 (We have tested on it.)

We are trying to give the concepts and code snippet for both Server side development and Client Side Development below.

Server Side -

A> ConnectionHelper.java – it is used for making connection with MySql Database.

B> Wine.java - it is used as simple POJO class for the table in database.

C> WineDAO.java – it is used to write JDBC related codes for insert/update/delete/select in the MySql Table. All the DB manipulation methods are written here.

D> WineResource.java – Important Class related to REST API Based Web Services. Method Signatures are given below -

@GET @Path("wines")
@Produces(MediaType.APPLICATION_JSON) 
public List findAll() {

    // to fetch all data from DB

}
@GET @Path("search/{query}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Wine> findByName(@PathParam("query") String query) {
   // to fetch particular data from DB on basis of product name.

}
@GET 
@GET @Path("{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Wine findById(@PathParam("id") String id) {
	//to fetch particular data from DB on basis of ID.
}
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Wine create(Wine wine) {
       // To insert the data in db with the simple POJO Wine
}
@PUT @Path("{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Wine update(Wine wine) {
	// For updating the Data with particular ID	
}
@DELETE @Path("{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public void remove(@PathParam("id") int id) {
	// to Delete the particular record with the selected ID
}

All the REST based API can be tested with the class

6>Test.java - 

particular line to test here -

System.out.println(service.path("rest").path("wines").accept(MediaType.APPLICATION_JSON).get(String.class));

Now a simple explanation on how the testing is happening for Jersey based REST Web Service -

We can dig into the web.xml further to see the lines -

<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.webphlox.brandserver.sample</param-value>
</init-param>

- for scanning the packages for REST based web service resources by Java Jersey Server.

<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

- for identifying the path for REST based web services which is here – /rest/

So in the above testing method,

service.path("rest")

is for url-pattern
and .path(“wines”) is for getting the particular method. And also it will send the output in json format.

Client Side -

HTML Part -

In client side, the index.html is for the backbone.js templates -

<script type="text/template" id="tpl-header">
<button class="new">New Wine</button>
</script>

- Here the Button is for New Data Add.

<script type="text/template" id="tpl-wine-list-item">
<a href='#wines/<%= id %>'><%= name %></a>
<!-- <%= id %> and <%= name %> are used as template variables.
</script>

- to show the Data list in a tabular format.

<script type="text/template" id="tpl-wine-details">

<div class="form-left-col">
<label>Id:</label>
<input type="text" id="wineId" name="id" value="<%= id %>" disabled />
<label>Name:</label>
<input type="text" id="name" name="name" value="<%= name %>" required/>
<label>Grapes:</label>
<input type="text" id="grapes" name="grapes" value="<%= grapes %>"/>
<label>Country:</label>
<input type="text" id="country" name="country" value="<%= country %>"/>
<label>Region:</label>
<input type="text" id="region" name="region" value="<%= region %>"/>
<label>Year:</label>
<input type="text" id="year" name="year" value="<%= year %>"/>
<button class="save">Save</button>
<button class="delete">Delete</button>
</div>

<div class="form-right-col">
<img height="300" src="pics/<%= picture %>"/>
<label>Notes:</label>
<textarea id="description" name="description"><%= description %></textarea>
</div>

</script>

- to show the particular data item details.

Javascript part (Backbone.js)

All the javascript related codes can be found in main.js.

First, we have to define the Model of Data to be handled by backbone javascript.

// Models 

window.Wine = Backbone.Model.extend({
urlRoot:"http://localhost:8080/brandserver/rest/wines",
defaults:{
"id":null,
"name":"",
"grapes":"",
"country":"USA",
"region":"California",
"year":"",
"description":"",
"picture":""
}
});

window.WineCollection = Backbone.Collection.extend({
model:Wine,
url:"http://localhost:8080/brandserver/rest/wines"
});

urlRoot is the REST based web service calling point (endpoint). Here we have specified the url which is needed to data select/insert/update/delete. Also the Model is Wine – which will be used to store data from web service endpoint and manipulate the data and it is part of collection - WineCollection.

The default parameter is used to initialize a new Model while adding the data.

There are three views in the Application

A> WineListView – contains a collection of Item View - WineListItemView

B> WineListItemView – responsible for rendering the  model template – WineView

C> WineView – contains core methods for adding,deleting and updating -

The interesting methods are – 1> saveWine and 2> deleteWine

D> HeaderView -responsible for initialize the view for adding a new template.

The interesting method is – newWine 

Router - AppRouter is responsible for initial routing of the Application.

So this is the Proof of Concept of Backbone.js with a Java based web Application.

We will dig in deeper for backbone.js data coding for Model, Collection, View and Router in context of this tutorial in separate posts.

So for now it is all.

Comments are welcome.

More Resources :

1> Backbone.js Lessons Learned and Improved Sample App

2> Learn Backbone.js Completely

Other Resources you may have interest :

1> Backbone.js in Client Side Javascript MVC – with Java based Web Project

2> Backbone.js Router in Client Side Javascript MVC – with Java based Web Project – Part 2

3> Backbone.js View in Client Side Javascript MVC – with Java based Web Project – Part 3

Enter your email address:

Delivered by FeedBurner

Filed in: Uncategorized