The key point is that when a script makes an "Ajax request" (XHR), the server doesn't know it came from a script, and handles it like any other request. One reason Ajax is so successful is that it works just fine with existing server technologies, including Struts.
It's not the Ajax request that is different, but the Ajax response. Instead of returning an entire page for the browser to display (or redisplay), an Ajax response will just return a portion of a page. The response can take the form of XML, or HTML, or plain text, another script, or whatever else the calling script may want.
Both Struts 1 and Struts 2 can return any type of response. We are not limited to forwarding to a server page. In Struts 1, you can just do something like:
In Struts 2, we can do the same thing with a Stream result.
There are easier ways!
Using a Struts 2 plugin (e.g., JSON plugin, jQuery plugin, etc.) is, in general, preferred to writing the response directly from within an action. See sections following this for further details.
On the client side, there are two basic strategies, which can be mixed and matched.
While Struts works fine with Ajax out-of-the-box, for added value, several Ajax-centric plugins are available.
Ajax Tag Plugins
- Dojo - The Ajax Tags Dojo Plugin was represented as a theme for Struts 2.0. For Struts 2.1, the Dojo tags are bundled as a plugin until version 2.3.x. Since version 2.5 this plugin is not part of th Struts2 distribution anymore
- YUI - The Yahoo User Interface (YUI) Plugin has only a few tags are available so far, but the YUI tags tend to be easier to use than the Dojo versions.
Other Ajax Plugins
- Ajax File Upload - With the Ajax File Upload Plugin we can upload a file to the server and asynchronously monitor its progress.
- GWT - The Google Web Toolkit Plugin exposes Struts 2 actions to the GWT RPC mechanism.
See the Struts Plugin Repository for a complete list of Struts 2 plugins.
Ajax Results with JSP
While server pages are most often used to generate HTML, we can use server pages to create other types of data streams. Here's an example:
In the code example, we use
System.out.println to return a JSON data stream as the response. For more about this technique, see the article Using Dojo and JSON to Build Ajax Applications.