Apache Struts 2 Documentation > Home > Guides > Core Developers Guide > AJAX
Added by Ted Husted, last edited by Dave Newton on Mar 10, 2007  (view change) show comment

AJAX is an acronym for Asynchronous JavaScript and XML. Essentially, a JavaScript can make a HTTP request and update portions of a page directly, without going through a conventional POST or GET and refreshing the entire page. Better yet, a page can contain several JavaScripts making simultaneous (asynchronous) requests.

AJAX is a client-side, user-interface technology that depends on a server-side component to provide business and data-access logic. Struts 2 makes an excellent backend to AJAX applications, especially when an application uses both AJAX and conventional requests. The elegant and extensible Struts 2 architecture makes it easy to tailor how different types of requests are processed.

There are at least three ways to use AJAX with Struts 2.

  • Ajax Tags
  • JSP results
  • Plugins

Ajax Tags

Ajax Tags are used by using the Ajax Theme with the Struts Tags. The tags are based on Dojo widgets and provide a quick and easy way to start using AJAX in your application.

JSP Results

A conventional request will often end with a forward to a server page that completes the response. In this case, the response is a HTML stream that the browser receives and renders. In the case of an AJAX call, the response is a data stream that the JavaScript receives and integrates into the page that the browser is already displaying.

The X in AJAX stands for XML, but, in practice, many other formats are used to transfer data between the AJAX frontend and server backend. Aside from XML, other popular formats are JSON (JavaScript Object Notation), plain text, and HTML snippets.

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:

book.jsp
<%@ page import="java.util.Iterator,
		 java.util.List,
		 com.esolaria.dojoex.Book,
		 com.esolaria.dojoex.BookManager" %>
<%
	String bookIdStr = request.getParameter("bookId");
	int bookId = (bookIdStr == null || "".equals(bookIdStr.trim())) 
		? 0 : Integer.parseInt(bookIdStr);
	Book book = BookManager.getBook(bookId);
	if (book != null) {
		out.println(book.toJSONString());
		System.out.println("itis: " + book.toJSONString());
	}
%>

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.

Plugins

Right now, there are two AJAX-centric plugins listed in the Struts Plugin Repository:

  • JSON Plugin - The JSON Plugin serializes Actions properties into JSON, making it easy to respond to JavaScript requests.

Next: Dependency Injection