JSF Search Application Using Ajax

Here, Roseindia Tutorial Section provides you a JSF search application using Ajax. This is a simple application in which, you will see two JSF components that one is the text box component which is for entering keywords whatever you have to search and sec

JSF Search Application Using Ajax

JSF Search Application Using Ajax


Here, Roseindia Tutorial Section provides you a JSF search application using Ajax. This is a simple application in which, you will see two JSF components that one is the text box component which is for entering keywords whatever you have to search and second one is the command button labeled with the "OK" text that is for submitting the form by clicking on that component. When you enter the keyword into the text box component for searching about the the keyword i.e. the title of the topic provided by the Roseindia Java Tutorial, during entering each and every character of the title this component shows you a popup below the text box component that holds some titles starting with the entered text into the text box component. This application is very useful for everybody who want to integrate into the any type of website. You can direct copy the given code and paste it into your application for constructing the application.

Search application in any type website makes the website reliable and very user friendly for visitors. Visitors can direct search the topic and getting the detailed explanation of the title for learning more. This application here using JSF and AJAX technology that mean this is based on the JSF and the AJAX technology. You can get the more about the JSF like what is JSF? and how does it work? in the Roseindia JSF Tutorial. This tutorial gives you the complete JSF tutorial from the starting point of the JSF to the professional level programming in JSF. You will just learn here about the integrating or using AJAX in the JSF. This section tells you about the procedure of using AJAX in JSF by providing the complete code for viewing and download also.

This section here introduces about the JSF and the AJAX technology:

AJAX: Ajax stands for Asynchronous JavaScript and XML. Ajax is used to fetch the data from web server without refreshing the whole page. JavaScript is used to send the request to web server in order to fetch the data. You can know more about the Ajax technology in detail by visiting the Roseindia Ajax Tutorial.

There are some JSP pages for viewing the the page by providing the JSF syntaxes, some Java Bean Classes for holding data temporarily, Servlet for handling the AJAX operation and a file that is for holding all data like the titles of the tutorial with the link regarding that and the full description also regarding the title of the topic have used for building the complete application. These files are illustrated as follows one by one:

Following some file names these have been used in the application:

  • index.jsp
  • search.jsp
  • web.xml
  • faces-config.xml
  • AjaxServlet.java
  • TitleBean.java
  • TitleRecord.java
  • SelectedTitleRecord.java
  • script.js

Directory structure of the application is pictured as follows:

Here is the code of the index.jsp page:

<jsp:forward page="/search.jsf" />

Here is the code of for the search.jsp page:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<head><title>Roseindia Search Page</title>
	<style type="text/css">
	     .box { position:absolute;border: 1px
			solid #000000; }
	     .result {
	   .title {
		font-family: Georgia, "Times New Roman", Times, serif;
		font-weight: bold;
		font-size: 24px;
	 .heading {
		font-family: Georgia, "Times New Roman", Times, serif;
		font-weight: bold;
		font-size: 16px;}
	<script type="text/javascript" language="JavaScript" src="js/script.js">

<body onload="initialize();">
		<h:outputText value="Roseindia Search Application" styleClass="title"/><br><br>
		<h:outputText value="Tutorial Search: " />
		<h:inputText id="autoText" onblur="hidePopup()" 
 		onfocus="getQuery(this.value)" onkeyup="getQuery(this.value)" 
 		value="#{SelectedTitleRecord.selectedTitle}" />
	<h:commandButton value="OK" action=""/>
	<h:outputText styleClass="heading" value="Title 
	Details" rendered="#{SelectedTitleRecord.selected}" />
	<h:outputLink value="#{SelectedTitleRecord.link}">
	<h:outputText value="#{SelectedTitleRecord.titlename}" />
		<h:outputText value="#{SelectedTitleRecord.description}" />
	<div align="left" class="box" id="autocomplete" style="width:170px;visibility:
	<script type="text/javascript" language="JavaScript">
	function initialize(){

Here is the code for the script.js file:

var req;

if (window.XMLHttpRequest) { 
     req = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");

var popupBoxName, textBoxName;

function initPopup(tBox, popupBox){
	popupBoxName = popupBox;
	textBoxName = tBox;
	var popupLayer = document.getElementById(popupBox).style;
	var qText = document.getElementById(tBox);

	var x = findPosX(qText);
	var y = findPosY(qText);

	var width = getWidth(qText);
	popupLayer.left = x + "px";
	popupLayer.top = (y + 22) +"px";

	popupLayer.width = width; 

function doMouseClick(val){
	var qText = document.getElementById(textBoxName);
	qText.value = val;

function hidePopup(){
	var popupLayer = document.getElementById(popupBoxName).style;

function showPopup(){
	var popupLayer = document.getElementById(popupBoxName).style;

function getQuery(key) {
	if (key=="") {
if (req.readyState != 0) {

var url = "/jsfajax/AjaxServlet?key=" + key;
	if (req != null) {
		req.open("GET", url, true);
		req.onreadystatechange = processResponse;

function processResponse() {
	if (req.readyState == 4){
		if (req.status == 200) {
			if(req.responseText==null) { 
			else {

function parseResponse(result){
	var xmlDoc;
	if(document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "", null);
	} else if (window.ActiveXObject){
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var count = xmlDoc.getElementsByTagName("TOTALCOUNT").item(0).getAttribute("count");

if(count != "0"){
	var fldValues = xmlDoc.getElementsByTagName("TITLE");
	var fldResult='';
	var values11 = new Array();
	for (var i=0;i<fldValues.length;i++){
	var val = fldValues.item(i).getAttribute("name");
	fldResult += '<SPAN class="result" onmouseover="this.style.color=
	\'blue\';" onmouseout="this.style.color=\'black\';" onmousedown="doMouseClick(\'' + val +
	'\');" >' + val + '</SPAN><BR>';
document.getElementById("autocomplete").innerHTML = fldResult;
	} else {
var isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);

	Document.prototype.loadXML = function (s) {
	var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
while (this.hasChildNodes())

for (var i = 0; i < doc2.childNodes.length; i++) {
this.appendChild(this.importNode(doc2.childNodes[i], true));

function findPosX(obj){
	var curleft = 0;
		if (obj.offsetParent){
			while (obj.offsetParent){
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
		else if (obj.x)
	curleft += obj.x;
	return curleft;

function findPosY(obj){
	var curtop = 0;
	if (obj.offsetParent){
	while (obj.offsetParent){
	curtop += obj.offsetTop
	obj = obj.offsetParent;
	else if (obj.y)
	curtop += obj.y;
	return curtop;

function getWidth(element){
	if (element.clientWidth && element.offsetWidth && element.clientWidth <element.
			offsetWidth) {
		return element.clientWidth;
	} else if (element.offsetWidth) {
		return element.offsetWidth;
	} else if (element.width) {
	return element.width;
	} else {
	return 0;

Here is the code of the AjaxServlet.java file:

package roseindia;

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

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");
 TitleBean titleBean = (TitleBean)getServletContext().getAttribute("TitleBean");
  String[] titles = titleBean.getTitles();
  String matches = getMatches(titles, key);
  java.io.PrintWriter out=response.getWriter();

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws java
.io.IOException, ServletException {
  doGet(request, response);

  private String getMatches(String[] titles, String key){
  String cList = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
  cList +="<TITLES>";
  int count = 0;
  for(int i=0;i<titles.length;i++){
  cList += "<TITLE name=\"" + titles[i] + "\" />";
  if(count == 5) break;
  cList += "<TOTALCOUNT count=\"" + count + "\" />";
  cList += "</TITLES>";
  return cList;

Here is the code of the TitleBean.java file:

package roseindia;

public class TitleBean{
 String[] titles;
 java.util.HashMap titleDetails = new java.util.HashMap();

 public static void main(String[] args){
  TitleBean tb = new TitleBean();

 public TitleBean(){
 System.out.println("Reading data from the file...");
 java.io.BufferedReader in=new java.io.BufferedReader(new java.io.InputStreamReader(

 } catch (java.io.IOException IOex) {
 System.out.println("IO Error :" +IOex);

 public java.util.HashMap getTitleDetails(){
 return titleDetails;

 public String[] getTitles(){
 return titles;
 private void readData(java.io.BufferedReader br) throws java.io.IOException  {
 int recordNum= Integer.parseInt(br.readLine());
 titles = new String[recordNum];
 for(int i=0; i<recordNum; i++){
 String line=br.readLine();
 java.util.StringTokenizer st=new java.util.StringTokenizer(line, "\t\r");
  String titlename= st.nextToken();
  String description= st.nextToken();
 String cont = st.nextToken();
 TitleRecord cr= new TitleRecord(titlename, description, cont);
 titleDetails.put(titlename, cr);
 titles[i] = titlename;

Here is the code of the TitleRecord.java file:

package roseindia;

public class TitleRecord {
  String titlename;
  String description;
  String link;
//  String capital;
//  String id;

  public TitleRecord(String titlename, String description, String link){
//  this.capital = capital;
//  this.id=id;

  public String getTitlename(){
  return titlename;

  public String getDescription(){
  return description;

  public String getLink(){
  return link;

Here is the code of the SelectedTitleRecord.java file:

package roseindia;

public class SelectedTitleRecord{
  String selectedTitle;
  TitleRecord selectedTitleRecord;
  java.util.HashMap titleDetails;

  public SelectedTitleRecord(){

  public String getSelectedTitle(){
  return selectedTitle;
  public void setSelectedTitle(String selectedTitle){
  this.selectedTitle = selectedTitle;

  public String getTitlename(){
  if(selectedTitleRecord != null) return selectedTitleRecord.getTitlename();
  else return null;
  public String getDescription(){
  if(selectedTitleRecord != null) return selectedTitleRecord.getDescription();
  else return null;

  public String getLink(){
  if(selectedTitleRecord != null) {
  if (selectedTitleRecord.getLink() != "") {
  String link = selectedTitleRecord.getLink().toLowerCase();
  return link;
  return null;
  public boolean isSelected(){
  if(selectedTitleRecord != null) return true;
  else return false;
  public void setSelectedTitleRecord(){
  if(selectedTitle != null) {
  Object obj = titleDetails.get(selectedTitle);
  if((obj != null) && (obj instanceof TitleRecord)){
  selectedTitleRecord = (TitleRecord) obj;
  } else selectedTitleRecord=null;
  } else selectedTitleRecord = null;
  public void setTitleDetails(){
  javax.faces.context.FacesContext context = javax.faces.context.FacesContext.
  javax.faces.application.Application app = context.getApplication();
  TitleBean cBean = (TitleBean) app.createValueBinding("#{TitleBean}").getValue(context);
  titleDetails = cBean.getTitleDetails();

Here is data in the title.data file:

1  2
2  Java Tutorial	This is the Roseindia Java Tutorial providing the complete java 
   solutions. This Tutorial gives you the complete java tutorial with some example which is
   ready to execute directly.	http://www.roseindia.net/java/
3  Java Swing Tutorial	This tutorial gives you the complete java swing tutorial.	

Download Complete Application.