Asynchronous JavaScript + XML (Ajax) is a fairly new term (some say it's old technology in new clothes) that's generating a good amount of buzz in various Web development communities, including the Java EE community. Ajax technology improves application usability by eliminating excessive Web page refreshes. And Ajax's best-of-both-worlds approach leverages client-side and server-side code to present an almost seamless UI to the Web user. Ajax is touted as one of the main enablers of Web movement's resurrection (dubbed Web 2.0).
As a diligent Java EE developer, you've probably read numerous how-to articles on Ajax and are excited about the possible improvements it can bring to your applications. But how will Ajax's asynchronous communication-based pattern fit into your Java EE applications? This article helps you answer this question by examining the impact of introducing Ajax on the design, development, performance, and testing of a Java EE application. My purpose isn't to discourage the use of Ajax or to imply that the problems you might encounter are inherent to Ajax technology. Rather, it's to help you plan for and thereby mitigate issues to make your use of Ajax effective and unintrusive.
For quite some time now, the Java community has been diligent in applying good design patterns to Web-related application development. One of the most widely used patterns is Model-View-Controller (MVC). Several open source frameworks, such as Apache Struts, are based on this design pattern/architecture (see Resources). MVC's several advantages include separation of concerns and decreased redundant code.
Separation of concerns lets each developer in a given application-development project focus on a specific role in by using prenegotiated interfaces throughout the application architecture. For example, model-layer developers focus on technologies such as JDBC, Enterprise JavaBeans (EJB) components, or Java classes that interface with underlying data-persistence technologies. View-layer developers focus on JavaServer Pages (JSP) technology, tag libraries, and other presentation-related technologies. The controller layer separates and mediates the model and view, routing incoming requests to back-end persistence calls while maintaining clear separation of concerns. Figure 1 illustrates the MVC architecture:
Figure 1. MVC architecture

Introducing Ajax into a Java EE Web application has implications for separation of concerns (and therefore separation of developer roles). In some cases, Ajax can introduce a large amount of JavaScript code back to the view-layer (JSP) page. Table 1 describes the MVC view layer without Ajax and indicates the amount of code needed, assuming that the controller layer is implemented by servlets and the view layer by JSP technology. (I'll explain the difference between synchronous and asynchronous requests in the next section, Dealing with development dilemmas.)
Table 1. MVC without Ajax: Amount of code related to a typical view-layer sequence
| Sequence | Description | Requires code? |
|---|---|---|
| Before invoking synchronous request | Scriptlet code required in preparing for form submission. | No. |
| Invoking of synchronous request | Form submission is invoked by button or link invocation; DOM element values are automatically set to HttpRequest (through either a GET or a POST). | No: All that is required is a way to invoke page submission. |
| Handling response to synchronous request | After server-side code finishes execution, typically, an object is sent back to the JSP (via HttpRequest or stored in HttpSession). At this point, the objects are accessible on the JSP via either HttpRequest or HttpSession (via scriptlet or some tag library), and minimal scripting is required to display contents of the object. | Yes: Minimal scriptlets. |
Contrast Table 1 with Table 2, which describes the MVC view layer with Ajax, again assuming that the controller layer is implemented by servlets and the view layer by JSP technology.
Table 2. MVC with Ajax: Amount of code related to a typical view-layer sequence
| Sequence | Description | Requires code? |
|---|---|---|
| Before invoking asynchronous request | JavaScript code is needed to retrieve values of the DOM elements required for Ajax call. | Yes |
| Invoking of asynchronous request | JavaScript code is required to create XMLHTTPRequest and associate (previously collected) values of DOM elements and send (XMLHTTPRequest.send()). | Yes |
| Handling response to asynchronous request | After server-side code finishes execution, JavaScript code is required to take the results (from XML response stream) and propagate values accordingly to appropriate DOM elements. | Yes |
You can see that the amount of scripting code in the view layer increases with the use of Ajax, causing three significant drawbacks:
- The JSP requires large amounts of JavaScript code.
- The design breaks the separation of role concerns.
- The design reintroduces monolithic JSPs (the Model 1 approach: a sea of HTML, CSS code, images, and scripting code), an antipattern that is extremely difficult to read and maintain (see Resources).
You have several options for avoiding or at least mitigating these design drawbacks:
- Design with reuse in mind: Unfortunately, scripting code specific to Ajax support is often difficult to avoid. Plan and design the scripting code so that you get maximum reuse from it.
- Employ a client-side MVC approach: You can incorporate a client-side MVC approach, as detailed Ajax in Action by Dave Crane et al. (see Resources). This approach promotes separation of concerns but adds complexity, so you should use it only with careful consideration.
- Use an Ajax framework: Several open source Ajax frameworks, such as Direct Web Remoting (DWR) (see Resources), do a good job of integrating the Ajax pattern into a Java EE application with minimal coding.
- Reassess the design's validity: Essentially, Ajax provides Web applications with desktop-application attributes. If most of the client-side interactions in a given Web application leverage Ajax, that application might well be better designed as a desktop application.
Dealing with development dilemmas
When you use Ajax in Java Web development, it is important to understand fully the difference between the synchronous and asynchronous communication models (see Resources). Lack of support for the asynchronous communication model can have an impact on client-side development, integration with Web frameworks, use of tag libraries, IDE use, and threading behavior.
In the synchronous request/response communication model, the browser (as opposed to the Web server, application server, or Web application) always initiates requests (via the Web user). In turn, the Web server, application server, or Web application responds to the incoming requests. During the processing of a synchronous request/response pair, the user can't continue to use the browser.
Figure 2 is a sequence diagram that illustrates traditional Web applications' synchronous communication model. Notice that in the server's lifeline, data submission from the client and the server-side processing are tightly coupled.
Figure 2. Synchronous communication sequence

In the asynchronous request/response communication model, the communication between the browser (via the Web user) to the Web server, application server, or Web application (and vice versa) is decoupled. During the processing of an asynchronous request/response pair, a Web user can continue to use the browser while the current asynchronous request is processed. Once asynchronous request processing is completed, an asynchronous response is communicated (from the Web server, application server, or Web application) back to the client page. Typically, during this process, the invocation has no impact on Web users; they don't need to wait for the response.
The sequence diagram in Figure 3 illustrates the asynchronous communication model. Take note of the first dataSubmission (with server-side processing) and the first dataSubmission returned, both circled in red. These sequences are decoupled. The illustration also highlights the important fact (detailed later in this section; see Threading issues) that in this mode, multiple submissions (threads) are more likely to occur.
Figure 3. Asynchronous communication sequence

When introducing Ajax into any Web application, development teams need to watch for several hazards, mainly related to the generated HTML page and how it interacts with the browser. These issues are well-documented in Chris Laffra's two-part Considering Ajax series (see Resources). Some of the important points to keep in mind are:
- Scripting might not be enabled: For various reasons, JavaScript support is disabled in many users' browsers.
- Cross-browser support increases code requirements: An application supporting multiple browsers and browser versions can require an increase in scripting code because subtle variations exist in the way a given browser interprets DOM elements (and therefore the JavaScript code that operates on those elements).
- JavaScript is not secure: In most browsers, JavaScript source code associated with an HTML page can be viewed by selecting the view source option. In using the Ajax pattern, ensure that the logic implemented in your scripting code is not sensitive.
Integration with Web frameworks
It's natural to try to integrate Ajax development with your Java EE Web framework of choice. But some Java EE Web frameworks do not (yet) offer out-of-the-box support for the asynchronous communication model. To appreciate the implications of this fact, you need to understand the way servlets handle synchronous versus asynchronous communication. Figure 4 shows the traditional servlet sequence for handling a synchronous request:
Figure 4. Servlet sequence for handling synchronous request

Figure 4 should appear rather familiar to Java EE Web developers. A request from the browser is initially handled by the controller servlet's service(). The servlet can retrieve any value(s) it needs from HttpRequest (either as a parameter or attribute). Once controller processing is done, the results are sent back into HttpRequest (or HttpSession), and the RequestDispatcher forwards (or includes) control back to the page.
Figure 5 shows the servlet sequence for handling asynchronous requests:
Figure 5. Servlet's sequence for handling asynchronous request

The sequence in Figure 5 is slightly different from the synchronous sequence. A request from the browser is initially handled by the controller servlet's service(). The servlet can retrieve any value it needs from HttpRequest (either as a parameter or attribute). Once controller processing is done, the content type of the HttpServletResponse must be set to XML. Also, the results of the controller logic are written out using the PrintWriter. At this point, use of the RequestDispatcher is bypassed.
This is the this exact (asynchronous) sequence that most Java EE Web frameworks do not support, causing integration with Ajax to be difficult. Portlet and JavaServer Faces (JSF) frameworks that don't support the asynchronous communication model face the same issue.
You have some options for overcoming this situation:
- Coexist with the Web framework: Instead of waiting for built-in Ajax support or forcing Ajax support in your framework of choice, you can provide a separate servlet to handle all asynchronous requests. DWR uses this approach. The downside of this approach is that the Ajax request cannot easily leverage your framework's features.
- Integrate with the Web framework: By using freely available extensions or writing a custom one, you can devise a way to integrate with your Web framework of choice.
- Migrate to frameworks that support Ajax: Newer frameworks are beginning to support the asynchronous communication model. One of them is Apache Shale (see Resources).
Heavy use of tag libraries (taglibs) is common in Java Web application development. Like many Java EE Web frameworks, some taglibs don't currently support the asynchronous communication model out of the box, leaving you without a way to translate data submitted via XMLHttpRequest into HttpServletRequest (and vice versa). In essence, taglibs that don't support asynchronous communication become nonfunctional during an invocation of an Ajax XMLHttpRequest call. Your options are:
- Abandon use of taglibs that don't support the asynchronous model: Migrate the code you now generate by taglibs to HTML/JavaScript code. (If the Web application is highly dependent on taglibs, this approach will eventually lead to an increase in view-layer page size.)
- Work around the problem: Use Ajax frameworks that already have a workaround for this problem. One example is DWR (see
ExecutionContext.forwardToString()). In this case, you can continue to use the taglibs you've been using. - Use Ajax-supporting taglibs: Use taglibs that support the asynchronous model, such as the Ajax JSP Tag Library (AjaxTags) (see Resources).
Development and debugging with IDEs
A slew of JavaScript debugging tools are available to aid developers in developing JavaScript solutions. However, traditional Java development environments don't let you examine values in XMLHTTPRequest and other idiosyncrasies related to Ajax.
One solution is to leverage the AJAX Toolkit Framework (ATF) (see Resources). ATF is an Eclipse plug-in with enhanced JavaScript editing features such as edit-time syntax checking, an embedded Mozilla Web browser, an embedded DOM browser, and an embedded JavaScript debugger. ATF also includes the Personality Builder function, which assists in the construction of IDE features for arbitrary Ajax run-time frameworks and thus adds to the supported set of run-time environments in the ATF.
In a typical synchronous Web application, some areas require a somewhat longer processing time for a button or link click. Impatient and inexperienced Web users often invoke multiple form submissions by clicking on the button or link more than once, expecting that this will help speed processing time. Other times, users think that a double-click is required (as it is in a desktop application). Multiple form submission in a Web application is harmless in some cases. In others, the side-effects can cause serious threading issues or race conditions (where multiple threads compete for the execution of a code block). For example, multiple clicks to the Transfer Funds button in a banking application could result in unintended multiple transfers.
A Web application that supports both synchronous and asynchronous communication models can find itself in a similar predicament if its functionality isn't properly analyzed and planned for. An application that supports both communication models might mix server-side invocations on a given page (that is, exclusively synchronous, exclusively asynchronous, and a mixture of synchronous and asynchronous). As in the multiple-click scenario, an asynchronous call might process a bit more slowly. And if the application doesn't prevent it, the user might invoke a synchronous call while the asynchronous thread is processing because the page does not refresh and therefore does not prevent further activity on the page. The end result is that the two threads are processed concurrently. Although not originating from the same button or link on the Web page, such situations can cause threading issues (similar to the multiple-click problem) on server-side code.
For example, take the transfer-funds page of a banking application, shown in Figure 6:
Figure 6. Transfer funds example

For the sake of this example, the Transfer Funds button, shown in red, invokes an Ajax call. The Logout link (in yellow) invokes a synchronous call. If an impatient or inexperienced user clicks the red button and the yellow link consecutively (and assuming both links have a common path in the code), a race condition can eventually occur.
In general, you have two ways to prevent this situation from occurring. The first is the client-side solution. Once a link or button is invoked, use JavaScript to ensure that further page submissions are prohibited until the current thread finishes executing. The second solution is to allow multiple thread submissions while relying on synchronization in server-side code to safeguard against race conditions. If you introduce synchronization to solve this problem, remember that Java EE Web components (servlets, portlets, JSF, and so on) are multithreaded. Be cautious about synchronizing large sections of code (especially code related to request/response life cycle processing). In effect, misuse of synchronization can turn the application into a single-threaded application, thereby decreasing throughput.
Overcoming performance pitfalls
Use of Ajax also has the potential to impact performance of a Java EE Web-based application. Two resources are potentially affected by the possibility of allowing additional threads per request.
First, the thread pool in the servlet container can be affected. A thread pool specifies the maximum possible number of threads allowed to run concurrently in a Web container. One thread is required for every client request. However, a client request does not necessarily equate to a user request. A browser might require several client requests per user request. For example, several client requests might be required for a user submitting a form (which entails submitting form values, retrieving GIF files, retrieving JavaScript files, and retrieving CSS files). If synchronous and asynchronous requests are allowed to be submitted concurrently, this situation can mean supporting at least one more thread consumption (for the Ajax request) per user request. Although the possibility of adding one more thread per user request doesn't seem like much, the impact is evident when the application is under load (when each additional thread per user request is multiplied by the average user count). Obviously, this situation has the potential to impact the servlet container's performance.
Another resource that can be affected is the database connection pool. Typical Java EE Web applications enable two types of sequences for a user request: shallow requests and deep requests. Shallow request are requests originating from the Web page that execute server-side code but do not access a persistence store (such as a database) to complete the request. Deep requests are requests originating from the Web page that execute server-side code but do access a persistence store to complete the request.
In the deep-request sequence (assuming a database connection is needed), these aspects of database connection pooling can be affected by allowing more threads:
- The average number of threads waiting for a connection
- The average wait time in milliseconds for a connection
- The average time the connection is in use
As a result, you might need to increase the average size of the connection pool or number of connections.
Java developers have been placing an increasing amount of emphasis on providing a unit-testing harness around Java SE and Java EE code. As the amount of in-browser JavaScript increases with the introduction of Ajax, a solid JavaScript unit testing framework is also called for. Among those now available are JsUnit, Selenium, and HttpUnit (see Resources).
These frameworks provide a harness to develop unit tests for JavaScript functions that manipulate DOM elements on Web pages. They also let you group unit tests into test suites. Selenium's browser compatibility testing feature lets you test JavaScript functions on different browsers and operating systems. It uses JavaScript and Iframes to embed a test automation engine in your browser. This technique should work with any JavaScript-enabled browser and is especially useful for applications that support multiple browsers and browser versions. Selenium and JsUnit both support continuous integration: you can integrate JavaScript unit tests and test suites into an automated build process.
Introducing Ajax -- just like any other technology or pattern -- into a Java EE application has its advantages and disadvantages. This article has given you the big picture of Ajax integration into Java EE Web applications. Ajax's asynchronous communication model is quite different from the synchronous model that traditional Java EE Web applications are built to support. To avoid being blindsided, be sure to apply ample forethought to the potential problem areas before taking the Ajax plunge.
Support for Ajax within Java EE frameworks and utilities continues to improve. Going forward, look to leverage frameworks with out-of-the-box Ajax support to reduce the complexity of the integration. JSF-based Apache Shale and servlet-based DWR are two that you'll want to keep an eye on.
Learn
- Web-Tier Application Framework Design: A brief Model-View-Controller reference from the Sun Blueprints site (including an explanation of the Model 1 antipattern).
- Using Custom Tags to Avoid Scriptlets: The Sun Blueprints site details of the advantages of avoiding scriptlets on the view layer.
- Synchronous and Asynchronous communication: Check out Wikipedia's definitions of these terms.
- Direct Web Remoting: DWR is an easy-to-use Ajax-for-Java framework.
- Ajax for Java developers: Explore Phil McCarthy's developerWorks series to learn more about the pleasures and pitfalls of integrating Ajax into a Java Web application development.
- Ajax JSP Tag Library: A set of JSP tag libraries that supports Ajax.
- Apache Struts: The de facto Java EE MVC framework.
- Apache Shale: The next evolution of Struts, based on JSF.
- "Shale isn't Struts" and "Anatomy of a Shale application" (Brett McLaughlin, developerWorks, February 2006): Popular author and frequent developerWorks contributor Brett McLaughlin introduces Shale in this multi-part article series.
- "Considering Ajax, Part 1" and "Considering Ajax, Part 2": (Chris Laffra, developerWorks, May 2006): A discussion of the impact of Ajax on browser use.
- Ajax in Action (Dave Crane et al., Manning Publications, 2005): A good Ajax book from Manning Publications that includes discussion of a client-side MVC approach.
- JsUnit, Selenium, and HttpUnit: Automated-testing frameworks for JavaScript.
- The Java technology
zone: Hundreds of articles about every aspect of Java
programming.
Get products and technologies
- AJAX Toolkit Framework: Technology from IBM alphaWorks that assists in constructing Eclipse framework support for Ajax toolkits and provides enhanced DHTML/JavaScript IDE features for Ajax developers.
Discuss
- developerWorks
blogs: Get involved in the developerWorks community.
- Ajax discussion forum: A community for Web developers just learning or actively using Ajax.

Patrick Gan is a senior information technology specialist with IBM Global Services. Patrick's expertise is in Java EE, object-oriented application development, and use of open source frameworks. Patrick primarily works on client engagements, assisting clients in the design and development phases of Java EE application development. He is also involved in the design, development, and maintenance of IBM-specific Java EE based frameworks. He has been with IBM for about six years and has a degree in computer science.
Comments (Undergoing maintenance)





