Skip to main content

Example Backbone.js , JAX-RS, JPA Application

Posted by caroljmcdonald on September 16, 2013 at 10:20 AM PDT

Backbone.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.

The Backbone.js Client architecture

Models contain the  data and  defines 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 which synchronize with the server. Collections can trigger  events to be notified when any model in the collection has been changed, add, remove , to 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:  

    Name: Sneaky Cat

    my cat is so sneaky

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.

The ItemFacadeREST get method returns a list of Post objects in JSON format.
  • 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/items/.
  • @GET specifies that the get method supports the HTTP GET method.
  • @Produces specifies the MIME types that a method can produce. The @QueryParam annotations specify input parameters for the get() method
  • @QueryParam specifies specify input parameters for the get() 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 marshalled 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:

Received:

 {"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 code  

Comments

You really explains good. I do not have more knowledge about ...

You really explains good. I do not have more knowledge about this but I have some knowledge that with the JPA tools in the product, you can use wizards to create and automatically initialize mappings.
Customization of Wordpress Theme

Your audience wants quality content that they can read ...

Your audience wants quality content that they can read easily. Use bold headings, lists and blockquotes can "hook, line and sinker" readers care about you and your message. However, the format of text in a web browser is not as easy or as familiar as formatting a text editing program such as Microsoft Word or using a WYSIWYG (what you see is what you get) text editor.
Learn HTML Codes