Enterprise Java Technologies Tech Tips
Tips, Techniques, and Sample Code
Welcome to the Enterprise Java Technologies Tech Tips for
November 22, 2005. Here you'll get tips on using enterprise
Java technologies and APIs, such as those in Java 2 Platform,
Enterprise Edition (J2EE) and Java Platform, Enterprise
Edition 5 (Java EE 5).
This issue covers:
* Using AJAX with Java Technology
* Converting a POJO to a Persistent Entity
These tips were developed using an open source reference
implementation of Java EE 5 called GlassFish. You can
download GlassFish from the GlassFish Project page
(https://glassfish.dev.java.net/).
You can view this issue of the Tech Tips on the Web at
http://java.sun.com/developer/EJTechTips/2005/tt1122.html.
You can download the sample archive for the AJAX tip at
http://java.sun.com/developer/EJTechTips/download/ttnov2005ajax-autocomplete.zip.
You can download the sample archive for the POJO objects tip at
http://java.sun.com/developer/EJTechTips/download/ttnov2005web-to-entity.zip.
Any use of this code and/or information below is subject to the
license terms at
http://developers.sun.com/dispatcher.jsp?uid=6910008.
See the Subscribe/Unsubscribe note at the end of this newsletter
to subscribe to Tech Tips that focus on technologies and products
in other Java platforms.
For more Java technology content, visit these sites:
java.sun.com - The latest Java platform releases, tutorials, and
newsletters.
java.net - A web forum for collaborating and building solutions
together.
java.com - Hot games, cool apps -- Experience the power of Java
technology.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
USING AJAX WITH JAVA TECHNOLOGY
by Greg Murray
AJAX stands for Asynchronous JavaScript and XML. In essence,
AJAX is an efficient way for a web application to handle user
interactions with a web page -- a way that reduces the need to
do a page refresh or full page reload for every user
interaction. This enables rich behavior (similar to that of
a desktop application or plugin-based web application) using
a browser. AJAX interactions are handled asynchronously in the
background. As this happens, a user can continue working with
the page. AJAX Interactions are initiated by the JavaScript
in the web page. When the AJAX interaction is complete,
JavaScript updates the HTML source of the page. The changes
are made immediately without requiring a page refresh. AJAX
interactions can be used to do things such as validate form entries
(while the user is entering them) using server-side logic, retrieve
detailed data from the server, dynamically update data on a page,
and submit partial forms from the page.
What is particularly attractive about this is that AJAX
applications do not require a separate plug-in, and are platform
and browser-neutral. That said, AJAX is not supported as well
in older browsers. Care needs to be taken in writing client-side
script that accounts for the differences between browsers. You
might consider using a JavaScript library that abstracts the
browser differences and in some cases support older browsers
using alternative interaction techniques. For more details, see
the "AJAX FAQ for the Java Developer"
(http://weblogs.java.net/blog/gmurray71/).
So Where Does Java Technology Fit In?
Java technology and AJAX work well together. Java technology
provides the server-side processing for AJAX interactions. It
can provide this through servlets, JavaServer Pages (JSP)
technology, JavaServer Faces (JSF) technology, and web services.
The programming model for handling AJAX requests uses the same
APIs that you would use for conventional web applications. JSF
technology can be used to create reusable components that
generate the client-side JavaScript and corresponding server-side
AJAX processing code. Let's look at an example that uses
AJAX and servlets.
Autocomplete Example
Imagine a web page in which a user can search for information
about an employee. The page includes a field where the user can
enter the name of the employee. In this example the entry field
has an autocomplete feature. In other words, the user can type
in part of the employee name, and the web application attempts
to complete the name by listing all employees whose first or
last name begins with the characters entered. The autocomplete
feature saves the user from having to remember the complete name
of the employee or from looking for the name on another page.
Implementing autocomplete in a search field is something that
can be performed using AJAX. To do it, you need to provide code
on the client and on the server.
On the Client
First, the user specifies the URL of a page that is loaded by
the browser. For this example let's assume the page is an HTML
page that is generated by a JSF component, servlet, or JSP page.
The page contains a form text field that has an attribute onkeyup
with the name of a JavaScript function doCompletion(). This
function is called each time a key is pressed in the form text
field.
Let's assume that a user types in an "M" character in the form
text field. In response, the doCompletion() function is called
which, in turn, initializes an XMLHttpRequest object:
function initRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function doCompletion() {
if (completeField.value == "") {
clearTable();
} else {
var url = "autocomplete?action=complete&id=" +
escape(completeField.value);
var req = initRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseXML);
} else if (req.status == 204){
clearTable();
}
}
};
req.open("GET", url, true);
req.send(null);
}
}
The XMLHttpRequest object is not currently part of standard
JavaScript (efforts are underway to standardize it), but is
a de facto standard and is the heart of AJAX. This object is
responsible for interacting over HTTP with a server-side
component (in this case, a servlet).
Three parameters are specified when you create an XMLHttpRequest
object: a URL, the HTTP method (GET or POST), and whether or not
the interaction is asynchronous. In the XMLHttpRequest example, the
parameters are:
o The URL autocomplete, and the text from the complete-field (an
M character):
var url = "autocomplete?action=complete&id=" +
escape(completeField.value);
o GET, signifying the HTTP interactions uses the GET method, and
true, signifying that the interaction is asynchronous:
req.open("GET", url, true);
A callback function needs to be set when you use asynchronous
calls. This callback function is called asynchronously at
specific points during HTTP interaction when the readyState
property on the XMLHttpRequest changes. In the example the
callback function is processRequest(). It's set as the
XMLHttpRequest.onreadystatechange property to a function. Notice
the call to the parseMessages function when the readState is "4".
The XMLHttpRequest.readyState of "4" signifies the successful
completion of the HTTP interaction.
The HTTP interaction begins when XMLHttpRequest.send() is called.
If the interaction is asynchronous, the browser continues to
process events in the page.
On the Server
The XMLHttpRequest makes an HTTP GET request to the URL
autocomplete, which is mapped to a servlet called AutoComplete.
The doGet() method of the AutoComplete servlet is called. Here is
what the doGet() method looks like:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
...
String targetId = request.getParameter("id");
if (targetId != null) targetId = targetId.trim().toLowerCase();
Iterator it = employees.keySet().iterator();
while (it.hasNext()) {
EmployeeBean e = (EmployeeBean)employees.get(
(String)it.next());
if ((targetId != null) &&
(e.getFirstName().toLowerCase ().startsWith(targetId) ||
e.getLastName().toLowerCase().startsWith(targetId))
&& !targetId.equals("")) {
sb.append("