Example Backbone.js, JAX-RS, JPA Application
Join the DZone community and get the full member experience.
Join For FreeBackbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface. JAX-RS provides a standardized API for building RESTful web services in Java. This example will show how to build a simple pet catalog application using Backbone.js and JAX-RS.




Models contain the data and define the methods related to the data. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.
Here is the source code for Item.js:
var ItemModel = Backbone.Model.extend({ urlRoot: "resources/items", defaults: { id: null, name: "", description:"", } });
Collections are ordered sets of models that synchronize with the server. Collections can trigger events to be notified when any model in the collection has been changed, add, remove, or fetch from the server.
Here is the source code for Items Collection Items.js:
var ItemList = Backbone.Collection.extend({ model: ItemModel, url: "resources/items", } }); var Items = new ItemList();
The model property specifies the model class that the collection contains.
The url property (or function) on a collection references its location on the server.
Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request. The default sync handler maps Fetch,Save,Destroy CRUD requests to REST using the collection url:
- Save (new) → create → HTTP POST /url
- Fetch → read → GET /url/id
- Save → update → PUT /url/id
- Destroy → delete → DELETE /url/id
The View
- A view is bound to a model/collection
- Manipulates the model data in the DOM
- Delegates DOM events
- Render function uses the model data to render the template
With the Backbone view you can bind your view's render function to the model's "change" event, then everywhere that model data is displayed in the UI, it will be updated.
Here is the source code for the Item View ItemView.js:
window.ItemView = Backbone.View.extend({ initialize: function () { this.render(); }, render: function () { $(this.el).html(this.template(this.model.toJSON())); return this; }, events: { "change" : "change", "click .save" : "beforeSave", "click .delete" : "deleteItem" }, });
In the view you override the render function, specify events, and in this example specify a template. In the code above, the initialize function binds the View to the change events of its model, which call the render function when the event is fired. The render function renders the view template from model data, and updates this.el with the new HTML.
This View renders the model data into HTML using a template engine.
<script type="text/template" id="item-template"> <h3>Name: {{name}}</h3> <p>{{description}}</p> </script>
- Model attributes: {"name":"Sneaky Cat","Description":"my cat is so sneaky"}
- Render method: this.$el.html(this.template(this.model.toJSON()));
- Template output: <h3>Name: Sneaky Cat</h3> <p>my cat is so sneaky</p>
The Catalog Items Database Table
The catalog items are contained in a database table:
- Item contains the title and text for each item in the catalog.
CREATE TABLE item ( id INT NOT NULL, productid VARCHAR(10) , name VARCHAR(30) , description VARCHAR(500) , imageurl VARCHAR(155), imagethumburl VARCHAR(155), price DECIMAL(14,2) , primary key (id) );
The Model – JPA Entity Classes
The Model is your application’s persistent business domain objects. A JPA Entity instance represents a row in a database table. Item is an Entity
class — a typical Java Persistence entity object — which maps to an Item table that stores the item instances.
Code sample from Item.java:
package model; ... @Entity @Table(name = "item") @XmlRootElement public class Item implements Serializable { @Id private Integer id; private String description; ... //getters and setters ...
RESTful Web Services with JAX-RS
The ItemFacadeREST class is a Root resource class. Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator, such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a request method designator. This section explains how to use JAX-RS to annotate Java classes to create RESTful web services.
- To address a resource in REST you specify its URI.
@Path
is a JAX-RS annotation that identifies the URI path for the resource. For the ItemsResource the URI path is/item
s
/.
@GET
specifies that theget
method supports the HTTP GET method.@Produces
specifies the MIME types that a method can produce. The@QueryParam
annotations specify input parameters for theget()
method@QueryParam
specifies specify input parameters for theget()
method
Here is part of the source code for the ItemsResource class:
@Stateless @Path("/items") public class ItemFacadeREST extends AbstractFacade<Item> { @PersistenceContext(unitName = "itemPU") private EntityManager em; @GET @Produces({"application/xml", "application/json"}) public List<Item> findAll() { CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(Item.class)); return getEntityManager().createQuery(cq).getResultList(); }
The findAll() method uses the EntityManager to create a Query object for executing Java Persistence query language statements that can return a list of items. The Item.class is annotated with @XmlRootElement making it a Java Architecture for XML Binding (JAXB)-annotated class which will be marshaled as a list of Item
objects into XML or JSON format.
Here is an example of an HTTP request for this Web Service:
Request: GET http://localhost:8080/blog/resources/items/1?
Here is an example of an HTTP response for this Web Service:
{"id":1, "productid":"feline01", "name":"Friendly Cat", "description":"This black and white colored cat is super friendly. Anyone passing by your front yard will find him puring at their feet and trying to make a new friend. His name is Anthony, but I call him Ant as a nickname since he loves to eat ants and other insects.", "imageurl":"anthony.jpg", "imagethumburl":"anthony-s.jpg", "price":307.10}
Source code download:
Example CodeReferences:
This example is based on:
http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/
Opinions expressed by DZone contributors are their own.
Trending
-
Core Knowledge-Based Learning: Tips for Programmers To Stay Up-To-Date With Technology and Learn Faster
-
Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
-
Understanding the Role of ERP Systems in Modern Software Development
-
Components of Container Management
Comments