Saturday, November 05, 2005

AJAX-MVC with Rico

     I recently re-did the PocoPay welcome page. It now shows an invoice, similar to a monthly statement like you would get with a credit card. It also has links to the invoices from past months. The past month functionality was a good candidate for some AJAX. After doing some AJAX with lots of custom JavaScript, I thought it was good time to try out an AJAX library.
     There are a ton of AJAX libraries out there, which is not surprising. It seems like one of the most common ones for Java apps is DWR. I considered using it, but I have some “philosophical” issues with it. I really hate scriptlets inside JSPs. I think this comes from bad experiences with such JSPs early on in my career. I’ve also had to deal with some really bad programmers who thought that the only way to program in Java was to do it in a scriptlet on a JSP page. So the idea of using DWR to directly invoke a business method just seems like a step backwards.
     So instead of using DWR, I chose to use Rico. I liked that it was built on Prototype, an object-oriented JavaScript library that is the basis for the excellent AJAX support in Ruby on Rails. In Rico, really allows for AJAX support similar to ROR’s with any server-side technology. Rico is also just a JavaScript library.
     Rico lets you register parts of your page that can be updated. It then makes the XMLHttpRequest for you, and when it gets the callback, it simply takes HTML from the response and uses it to replace the corresponding part of the page. That means that your response just needs to create some XHTML that is wrapped in a little XML. I really like this because the XML/XHTML response is really just another view in the application that happens to be consumed by a JavaScript callback function instead of a web-browser. PocoPay already had similar non-HTML views used by the VoiceXML scripts.
     For my app (PocoPay), I use Spring MVC. I basically created a new model (command,) controller (simple command controller,) and view (just a clean JSP that declares itself as XML.) All of the parts of the page I wanted to be updated I simply wrapped in <div> tags. I then registered these divs and my view returned the new HTML for them. That was it! No crazy JavaScript to learn. It was truly AJAX-MVC to boot.      

No comments: