2010-01-31

REST with Spring 3.0, Spring MVC and Dojo. Part 2 - GET from Dojo perspective

In part 2 of the REST with Spring 3.0, Spring MVC and Dojo series we will take a look at the Dojo part of the story - that is how to read data via REST when you're a RESTful service client.

Operation REST method Sample URI
Return item(s) GET /books (all books)
/books/ (all books)
/books/12 (one book with ID = 12)
Create a new item POST (you pass the ID in the object itself)
/books
/books/
Update an item PUT (you pass the ID in the object itself)
/books
/books/
Delete an item DELETE /books/12 (book with ID = 12)

I will show you some very basic Dojo code so that you can get the idea. Dojo is a client side technology, written in JavaScript, and it doesn't care whether the service behind REST is implemented in Java or any other language.

Let's look at the sample code. Any HTML page can handle this, you don't even need a servlet container.

// I got the idea from an IBM tutorial.
function _request(method, xhrArgs) {
    if (!xhrArgs.url) {
        var deferred = new dojo.Deferred();
        deferred.errback();
        return deferred;
    }
    xhrArgs.url = xhrArgs.url;
    return dojo[method](xhrArgs);
}

This is a helper function to handle server requests that we will use for GET, PUT, POST and DELETE requests. It uses a Deferred object. Deferred is Dojo's way of handling "threads" and asynchronous matters. This is an important thing to mention: the calls we will make are asynchronous.

Now, let's see the actual code that gets stuff from the server using the function mentioned above. The first code snippet shows a function that gets all the books.

function retrieveBooks() {
    var deferred = _request("xhrGet", {
        url: "http://localhost:8080/restsample-0.0.1-SNAPSHOT/rest/books.json",
        handleAs: "json"
    });
    deferred.addCallback(this, function(value) {   
        // put retrieved picklists in select.options[]
        var books = value.books;
        alert(books.length + " books retrieved.");
        if (books.length > 0) {
            alert("The first retrieved book is: " + books[0].name);
        }
    });
    deferred.addErrback(this, function(value) {                
          alert("Error while retrieving books: "  + value);
    });
}

Okay, so that is a simple (and quite useless in real life because it only alerts the results) function that gets data using our previously defined _request function.

xhrGet is a Dojo function. It specifies that we want to call a GET method (and not a PUT etc.).

Next, we specify the address. Note that it ends in .json just in case the browser decides to get XML instead (even though we defined JSON as default).

Then we add callbacks, one for success (addCallback) and one for error handling (addErrback). Look how easily data is read, that's thanks to JSON. No evil eval, no explicit parsing. Why callbacks? Well, that's exactly because the call is asynchronous and we do not precisely know when we are going to get results.

The error callback will handle 500, 404 and other HTTP error codes. That's right. When a server side exception occurs the error callback is called.

Let us also look at a function that retrieves just one book instead of all:

function retrieveBook(bookId) {
    var deferred = _request("xhrGet", {
        url: "http://localhost:8080/restsample-0.0.1-SNAPSHOT/rest/books/" +
            bookId + ".json",
        handleAs: "json"
    });
    deferred.addCallback(this, function(value) {   
        // put retrieved picklists in select.options[]
        var book = value.book;
        alert("The retrieved book is: " + book.name);
    });
    deferred.addErrback(this, function(value) {                
          alert("Error while retrieving book: "  + value);
    });
}

It should now be self explanatory.

Download source code for this article

  1. REST with Spring 3.0, Spring MVC and Dojo. Part 1 - GET
  2. REST with Spring 3.0, Spring MVC and Dojo. Part 2 - GET from Dojo perspective
  3. REST with Spring 3.0, Spring MVC and Dojo. Part 3 - POST and JSR-303 validation
  4. REST with Spring 3.0, Spring MVC and Dojo. Part 4 - PUT (updating objects)
  5. REST with Spring 3.0, Spring MVC and Dojo. Part 5 - DELETE

42 comments:

  1. Replies
    1. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Now, since there are hundreds of millions of people using this technology, the amount of data must be large too. data science course syllabus

    ReplyDelete
  4. Wow what a Great Information about World Day its exceptionally pleasant educational post. a debt of gratitude is in order for the post.
    data science course in India

    ReplyDelete
  5. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    Data Science
    Selenium
    ETL Testing
    AWS
    Python Online Classes

    ReplyDelete
  6. A decent blog consistently concocts new and energizing data and keeping in mind that perusing I have feel that this blog is truly have each one of those quality that qualify a blog to be a one.
    AWS Training in Hyderabad
    AWS Course in Hyderabad

    ReplyDelete