Level: Intermediate
Philip McCarthy ([email protected]), Software development consultant, Independent
08 Nov 2005
Exciting as it is, adding Ajax functionality to your
applications can mean a lot of hard work. In this third article in the
Ajax for Java developers series, Philip McCarthy shows you how to
use Direct Web Remoting (DWR) to expose JavaBeans methods directly to your
JavaScript code and automate the heavy-lifting of Ajax.
Understanding the fundamentals
of Ajax programming is essential,
but if you're building complex Ajax UIs, it's also important to be able to work at a higher level of abstraction. In this third article in the Ajax for
Java developers series, I build on last month's introduction to
data
serialization techniques for Ajax, introducing a technique
that will let you avoid the nitty-gritty details of serializing Java
objects.
In the previous article, I showed you how to use JavaScript Object Notation (JSON) to serialize data in a format easily converted into JavaScript objects on the client.
With this setup, you can invoke remote service calls using JavaScript
code and receive JavaScript object graphs in response, not unlike making
a remote procedure call. This time, you learn how to take things one
step further, using a framework that formalizes your ability to make remote
procedure calls on server-side Java objects from JavaScript client
code.
DWR is an open source, Apache licensed
solution consisting of server-side Java libraries, a DWR servlet, and
JavaScript libraries. While DWR is not the only Ajax-RPC toolkit
available for the Java platform, it is one of the most mature, and it
offers a great deal of useful functionality. See Resources to download DWR before proceeding with
the examples.
What is DWR?
In the simplest terms, DWR is an engine that exposes methods of server-side Java objects to JavaScript code. Effectively, with DWR, you can eliminate all of the machinery of the Ajax request-response cycle from your application code. This means your client-side code never has to deal with an XMLHttpRequest object directly, or with the server's response. You don't need to write object serialization code or use third-party tools to turn your objects into XML. You don't even need to write servlet code to mediate Ajax requests into calls on your Java domain objects.