Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.


This post first appeared on Geo Coding, please read the originial post: here

Share the post

Tutorial: Using Ajax in a JSF application - II

×

Subscribe to Geo Coding

Get updates delivered right to your inbox!

Thank you for your subscription

×