Tutorial: Using Ajax in a JSF application - II
In part I, we have created a simple JSF application. Next we will implement Ajax into this application. This will require us to create i) a server side application to dynamically provide the data to the client and ii) client side javascript functions to request data and process the response.Step 1: Create the servlet as a server side application.
Copy the following code and save it as AjaxServlet.java in ajax/Web-Inf/classes/demo folder:
package demo;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AjaxServlet extends HttpServlet {
private ServletConfig servletConfig = null;
public void destroy() {
servletConfig = null;
}
public ServletConfig getServletConfig() {
return (this.servletConfig);
}
public String getServletInfo() {
return (this.getClass().getName());
}
public void init(ServletConfig servletConfig)
throws ServletException {
this.servletConfig = servletConfig;
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException,
ServletException {
String key = (String)request.getParameter("key");
//get CountryBean object from ServletContext
CountryBean countryBean = (CountryBean)
getServletContext().getAttribute("CountryBean");
//get list of countries
String[] countries = countryBean.getCountries();
//find matches
String matches = getMatches(countries, key);
//print it out to the client
response.setContentType("text/xml");
java.io.PrintWriter out=response.getWriter();
out.print(matches);
out.flush();
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException,
ServletException {
doGet(request, response);
}
private String getMatches(
String[] countries, String key){
//generate xml response
String cList = "<?xml version=\"1.0\" ";
cList += "encoding=\"UTF-8\" ?>";
cList +="<COUNTRIES>";
int count = 0;
//from countries list find first 5 matches
for(int i=0;i<countries.length;i++){
if(countries[i].toUpperCase().
startsWith(key.toUpperCase())){
cList += "<COUNTRY name=\"" + countries[i] + "\" />";
count++;
if(count == 5) break;
}
}
cList += "<TOTALCOUNT count=\"" + count + "\" />";
cList += "</COUNTRIES>";
return cList;
}
}
In doGet method of the above code, we first get the value of "key"
parameter submitted from the client. Next, we get the JSF managed
CountryBean from which we obtain a list of countries and store
it in a String array:
CountryBean countryBean = (CountryBean)
getServletContext().getAttribute("CountryBean");
//get list of countries
String[] countries = countryBean.getCountries();
We then call getMatches method to check for country names that start with the key string sent by the user. This is, of course, a very simple method but you can substitute it with your own advanced code.
Notice also that this method generates an XML document with a list of matching country names. Finally the XML document is sent to the client.
Step 2: Configure the Servlet
Open web.xml file from ajax/WEB-INF folder and add the custom servlet right after Faces Servlet:
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>demo.AjaxServlet</servlet-class>
</servlet>
Add this servlet mapping after Faces Servlet mapping:
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/AjaxServlet</url-pattern>
</servlet-mapping>
Step 3: Add javascript code to the application
Download the script.js file from here and copy it to ajax/js folder.
Notice in the js file that the following code creates the XMLHTTPRequest object.
(Also notice the difference in the code for creating this object in IE vs Mozilla.)
var req;
//initialize the XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
The function initPopup is responsible for turning off the autocomplete
feature of the browser. It also gets the location of the autocomplete
text-box and positions the popup element right below it. We will call
this function after the page is loaded.
The function doMouseClick is called when an item is selected in
popup list. This function sets the item value to the text box.
The functions hidePopup and showPopup simply hide and show the
popup element.
The function getQuery uses the XMLHttpRequest object and submits
the current text-box value to the AjaxServlet. Notice the path to our custom AjaxServlet configured above and how the key value is appended to the URL:
var url = "/ajax/AjaxServlet?key=" + key;
Also, notice the following line in this function:
req.onreadystatechange = processResponse;
The above line indicates that the processResponse function is called
when the response is received by the client. The processResponse
function forwards the response to parseResponse function.
The parseResponse function processes the response from the server.
Remember that the response is an XML document. So this function parses the XML document using dom parser and extracts the country names.
The country names will then be added to the popup CSS element which will then be displayed by setting its visibility to true.
The following code is required for Mozilla since it does not implement loadXML method by default.
//check if it is IE
var isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);
//implement loadXML method for Mozilla since it is not supported
if(!isIE){
Document.prototype.loadXML = function (s) {
// parse the string to a new doc
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
// remove all initial children
while (this.hasChildNodes())
this.removeChild(this.lastChild);
// insert and import nodes
for (var i = 0; i < doc2.childNodes.length; i++) {
this.appendChild(this.importNode(doc2.childNodes[i], true));
}
};
}
Step 4: Reference the javascript code in JSP page
Add this line within the HEAD of jsp code:
<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript" SRC="js/script.js"></SCRIPT>
Step 5: Enable ajax for input text
Modify the inputText component as follows:
<h:inputText id="autoText" onblur="hidePopup()" onfocus="getQuery(this.value)" onkeyup="getQuery(this.value)" value="#SelectedCountryRecord.selectedCountry}" />
Notice that on-focus and on-key-up (i.e. whenever a key is pressed
and released), we call getQuery function to submit a new request
to the server to get updated list. On-blur, we hide the popup list.
Step 6: Create popup div element
Add this code right before the end tag for body:
<div align="left" class="box" id="autocomplete"
style="WIDTH:170px;visibility:hidden;
BACKGROUND-COLOR:#ccccff">
</div>
<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">
initPopup('_id0:autoText','autocomplete');
</SCRIPT>
First we define the div element for popup. We then call initPopup javascript
function to size and position the popup element.

9 Comments:
Informative blog. I have a counter page xhtml blog.
Though this blog is good, it is actually incomplete, and contains several omissions in the code.
Refer to the zip file under http://kafle.blogspot.com/2005/08/using-ajax-in-simple-jsf-application.html for a complete example. This contains the essentail missing details, such as those in country.jsp.
This development approach is way to slow for large applications. I need JSF-components that support ajax out of the box.
Thanks anyway for a technical solution.
Search engines try it
Casino
viagra
tramadol
cialis
DOn't you know what else can help ? Because I do not know to whom address.
I was prescribed Carisoprdol which I bought here. But maybe I bought something wrong?
soma
soma
or here phentermine
how to call a JSF Managed bean using AJAX?
Great site buddy . Really I like ur site I think u r also a Java Developer like me any ways I have some reference books of java which are readable .... Following are the books
Programmer's Guide to Java
Certification A Comp. Primer SE
By Khalid A. Mughal, Rolf W. Rasmussen Publisher : Addison Wesley
Pub Date : August 04, 2003
Java™ Development on PDAs
Building Applications PocketPC
By Daryl Wilding-McBride Publisher : Addison Wesley
Pub Date : June 05, 2003
Learning Java™, 2nd Edition
Publisher : O'Reilly Pub Date : July 2002
Pub Date : June 05, 2003
Jython for Java Programmers
By Robert W. Bill Publisher : New Riders Publishing
Pub Date : December 21, 2001
Enterprise JavaBeans, 3rd Edition
By Richard Monson-Haefel Publisher : O'Reilly
Pub Date : September 2001
Java 1.5 Tiger: A Developer's Notebook
By David Flanagan, Brett McLaughlin Publisher : O'Reilly
Pub Date : June 2004
Java Tutorials Index 1
Java Data Objects
By David Jordan, Craig Russell Publisher : O'Reilly
Pub Date : April 2003
Java™ Extreme Programming Cookbook
By Eric M. Burke, Brian M. Coyner Publisher : O'Reilly
Pub Date : March 2003
Java™ Performance Tuning, 2nd Edition
By Jack Shirazi Publisher : O'Reilly
Pub Date : January 2003
Java™ Performance Tuning, 2nd Edition
By Jack Shirazi Publisher : O'Reilly
Pub Date : January 2003
JavaScript & DHTML Cookbook
By Danny Goodman Publisher : O'Reilly
Pub Date : April 2003
Java Servlet & JSP Cookbook
By Bruce W. Perry Publisher : O'Reilly
Pub Date : January 2004
Java Tutorials Index 2
How can I combine Icefaces to the ESRI webadf application?
The results of an Task should be viewed directly on an IceFaces component. IceFaces automates the AJAX communication.
Thamls
Hi,
I found a solution.
Check it here:
http://www2.pch.etat.lu/pchViewer
Post a Comment
<< Home