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

24 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. In the last couple of years, REST has emerged as a compelling alternative to SOAP/WSDL/WS-*-based distributed architectures. Therefore, I would like to thank you for your efforts in writing this innovation management thesis topics
    article. All content has been thoroughly researched. Thank you very much...

    ReplyDelete
  3. I am going to write a few posts on RESTful application development ,apple pencil 2 price in pakistan with Spring 3.0, using Spring MVC, Dojo and Maven.

    ReplyDelete
  4. Blockchain technology is revolutionizing the way we think about data and transactions, and the demand for experienced developers in this field is growing rapidly. The Spring MVC framework is a great way to create powerful, secure applications that make use of blockchain technology. With its robust set of features, such as support for multiple languages, easy integration with existing systems, and support for a variety of databases, Spring MVC provides an ideal platform for top blockchain developers to create amazing applications. If you're looking for a great way to get started in the blockchain development world, Spring MVC is definitely worth exploring.

    ReplyDelete
  5. I recently started using Insights Artist with Spring 3.0 and Spring MVC, and I'm really impressed with how easy it makes creating REST APIs. The documentation is really well written and the tutorials are extremely helpful. I've been able to quickly set up my API endpoints and handle requests with ease. I'm looking forward to exploring more of Insights Artist's features and capabilities.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. I am really appreciated your work to post a valuable blog. I gained a more information about this. I wanna see more posts like a good content. I always prefer to read a good quality content...I found this blog very helpful.
    Abogado De Divorcio En Virginia

    ReplyDelete
  8. I'm glad you mentioned the topic of reading data through RESTful service as a client. It's an important part of the development process. When you're in the market to buy computer processors, it's essential that you know the basics of this process. Thanks for sharing!

    ReplyDelete
  9. Blog.m1key.me is a personal blog authored by an individual who shares their experiences, thoughts, and perspectives on a variety of topics. From technology and travel to personal anecdotes, the blog provides a glimpse into the author's world and offers readers an opportunity to explore a diverse range of engaging content.
    Abogado DUI Southampton VA




    ReplyDelete
  10. "REST with Spring 3.0, Spring MVC, and Dojo - Part 2: GET from Dojo Perspective" is a comprehensive book on RESTful web services, focusing on the Dojo framework's role in handling GET requests, providing practical guidance for developers and enhancing their web development skills. Divorcio Colaborativo Nueva York

    ReplyDelete
  11. Thank you for the useful information, it's really appreciated. PunchedMC is a brand-new Minecraft Server List with custom plugins and achievements in its 1.12.2 Survival – a unique experience for Minecraft enthusiasts.

    ReplyDelete
  12. With its intuitive configuration and modular design, developers can quickly create RESTful applications while leveraging Spring's dependency injection and inversion of control principles. REST with Spring 3.0 empowers developers to build high-quality REST APIs efficiently. Motorcycle accident

    ReplyDelete
  13. The information is well-researched and interesting, and your writing style is captivating.criminal lawyers in prince william county va

    ReplyDelete
  14. "Programming REST with Spring 3.0" is a comprehensive guide that dives deep into creating RESTful web services with the latest version of Spring. This book is an essential resource for both beginners and experienced developers. It covers everything from the basics of REST architecture to advanced topics like security, testing, and integration with other technologies. The examples are practical and easy to follow, providing a solid foundation and best practices for building robust, scalable REST APIs. Whether you're looking to learn REST for the first time or update your skills to the latest Spring framework, this book is a must-read.

    District Of New Jersey Local Rules Protective Order

    ReplyDelete