Tutorial: Create Autocomplete feature with Java – JSP / jQuery
- By Viral Patel on June 8, 2009
Autocomplete is a common feature available in lot of web tools and services. You will find lots of implementation of autocomplete features. Let us see how can we implement a simple Autocomplete feature for Country names in Java-JSP and jQuery.
Related: Spring MVC – AutoComplete tutorial with JSON & JQuery
We will use jQuery’s autocomplete plugin for our example. Just go to JQuery Autocomplete UI page and download JQuery UI JS and CSS files. I have used Eclipse for the development of this demo.
Create a dymanic web project by clicking File -> New -> Project -> Dynamic Web Project and name it AutocompleteExample.

Once the project is created, create a package net.viralpatel.autocomplete and a Java class file DummyDB.java. DummyDB.java is the class that will simulate the database connection and it will provide the data for our example.

Following is the content of DummyDB.java.
package net.viralpatel.autocomplete;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class DummyDB {
private int totalCountries;
private String data = "Afghanistan, Albania, Zimbabwe";
private List<String> countries;
public DummyDB() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while(st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
totalCountries = countries.size();
}
public List<String> getData(String query) {
String country = null;
query = query.toLowerCase();
List<String> matched = new ArrayList<String>();
for(int i=0; i<totalCountries; i++) {
country = countries.get(i).toLowerCase();
if(country.startsWith(query)) {
matched.add(countries.get(i));
}
}
return matched;
}
}
The DummyDB.java contains the list of all the countries in a comma separated string value and a method getData () that will return the list of countries starting with the string query passed as argument to that method. Thus if we pass “IN” to this method, it will return as all the countries starting with IN.
You may want to change this code and add the database implementation here. Just a simple “SELECT * FROM <table> WHERE country LIKE ” query will serve the purpose.
Once this is done, we will create the JSP files that will be called by the autocomplete plugin to get the data. Download jquery.autocomplete.css and jquery.autocomplete.js as you will need it in our demo.
Copy jquery.autocomplete.css into css folder in WebContent and jquery.autocomplete.js into js folder.

Create index.jsp and paste following code into it.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="js/jquery.autocomplete.js"></script>
<style>
input {
font-size: 120%;
}
</style>
</head>
<body>
<h3>Country</h3>
<input type="text" id="country" name="country"/>
<script>
$("#country").autocomplete("getdata.jsp");
</script>
</body>
</html>
Update: In above code I have removed the old way of including jQuery library from Google AJAX API and changed it to simple <script> tag.
index.jsp will have a textbox “country” and it calls the server code for doing autocompletion by calling following code:
$("#country").autocomplete("getdata.jsp");
Note that the #country is the id of the textbox where we want to add autocomplete feature and the “getdata.jsp” is the server script that gets called.
Next, Create getdata.jsp and copy following code into it.
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="net.viralpatel.autocomplete.DummyDB"%>
<%
DummyDB db = new DummyDB();
String query = request.getParameter("q");
List<String> countries = db.getData(query);
Iterator<String> iterator = countries.iterator();
while(iterator.hasNext()) {
String country = (String)iterator.next();
out.println(country);
}
%>
getdata.jsp will just call DummyDB class’s getdata method to fetch list of countries and print it in the response. One thing we need to note here is that the Autocomplete plugin will take input separated by line feed, that is the list of countries should come in separate line. Following can be the desired output:
Denmark Djibouti Dominica Dominican Republic East Timor Ecuador
Execute the code in eclipse and you will get the desired output:

Download Source Code
Get our Articles via Email. Enter your email address.
Really nice works like a charm. Thank you
this is
very good example
please give example on struts2 hibernate
Thanks Malli, here is the Struts2+Hibernate example you looking for: http://viralpatel.net/blogs/tutorial-struts2-hibernate-example-eclipse/
Very nice explanation..working example..kudos..
Hi Viral,
I am using the above example with Spring Mvc and trying to load getdata.jsp but it is not showing any value inside index.jsp’s textbox. I am passing value from spring controller to jsp in a request object as an attribute. If u help me in this that wwould be really nice.
Where from this “q” comes? As there is no parameter whose name is q in index.jsp
String query = request.getParameter(“q”);
As said Jatin,
does anybody know where that
String query = request.getParameter(“q”);
comes from ??
if you remove or change the “q” in something else, it simply doesnt work anymore !!!
That is driving me insane…
look at jquery.autocomplete.js, line 337:
function makeUrl(q) { var url = options.url + "?q=" + encodeURI(q); for (var i in options.extraParams) { url += "&" + i + "=" + encodeURI(options.extraParams[i]); } return url; };really nice example understand easily for freshers:)
Hi… I am getting the following error… what i’ii do…
HTTP Status 500 –
——————————————————————————–
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /getdata.jsp at line 10
7:
8: String query = request.getParameter(“q”);
9:
10: List countries = db.getData(query);
11:
12: Iterator iterator = countries.iterator();
13: while(iterator.hasNext()) {
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:521)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
java.lang.NullPointerException
net.viralpatel.autocomplete.DummyDB.getData(DummyDB.java:23)
org.apache.jsp.getdata_jsp._jspService(getdata_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
As said Jatin,
does anybody know where that
String query = request.getParameter(“q”);
comes from ??
if you remove or change the “q” in something else, it simply doesnt work anymore !!!
That is driving me insane…
above example is very nice and super.
hi viral. i want help form you if u wish to do.i m new to java. i want to view sub ordinate hierarchy in tree structure in jsp while i was using common table expression in java it give error. however if you any example in related to this can u send me ashwinjava12@gmail.com …Thanks in advance and hoping some good suggestion related same………it help me to complete my intern
Is there any specification is available to get hierachy or Ranking to display in tree structure in jsp.
Appreciate your help and also your blog is very useful to me.
Thanks a lot, Very nice example.
super example……..
hi viral sir, it was really a workable and good example, but if you dont mind can u explain its flow, i mean how values are coming inside textbox and how we are able to select them.Is it possible due to the jquery APIs??
also why we are getting “q” as a parameter here?Kindly explain
rest it is all ok i could meet my objective……..
Hi Viral,
First of all this is really a fantastic example. I have a question and its troubling a lot. the question is I am trying to use a method along with .autocomplete forexample select: function()
i.e. $(“#country”).autocomplete(“getdata.jsp”, {select: function(){alert(“hello”);}); I tried a lot but failed, please if you can tell me how can I use another method in this example would be great. My requirement is select multiple values in a text box. For example india, australia, austria
regards,
S
Hello sir, it is working fine but its working slow and some time it does not take the values and can we improve its UI…………….
thanks
Thanks a lot. This is a very good example. Could you please give me another example on how to add the database implementation as you mentioned?
I wanted to this script in the external javascript file. But it is not working .
Please help me out on this
$(“#country”).autocomplete(“getdata.jsp”);
Good one but according to Oracle need to change the StringTokenizer part to split.
“StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.”