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.
We will use jQuery’s autocomplete plugin for our example. 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:

Get our Articles via Email. Enter your email address.
it doesn’t work ;(
sorry but it doesnt work …
Plain and simple
it does work…thanks !
Hey is there an other solution then to out.println(country); ??
Maybe to return an array from an controller jsp or something else?
Hi
From where are we passing this value?
String query = request.getParameter(“q”);
Thanks
for some reason when I include
on my page, other css will break and is not visible the web site as I want it..
is there any solution for it? thank you
I meant when I enclude that script that calles jsapi of the google javascript..
for some reason when I include
on my page, other css will break and is not visible the web site as I want it..
is there any solution for it? thank you
is it possible to tell me how i can add a flag with the county name.
Fantastic. Thanks a million. Worked perfectly!
JAVA RULES!!!
hello viral, i has try your code, but not display data in textbox and no errors. how to solve??
Error: $(“#country”).autocomplete is not a function
Thanks …Works perfectly. Very simple.
Though simple app running on Tomcat 5.x but seems to be very slow.
This is not working , I m not getting what is q in getdata.jsp
It is not working to me, I tried changing getdata.jsp parameter to input name which is country. But still I can’t make it to work.
Its really……..simple but much effective…..
“object doesn’t support this property or method” occurs in
$(“#country”).autocomplete(“getdata.jsp”);
what is the problem, can anyone tell me…
@Mahesh – It seems the autocomplete plugin is not properly included in your html. Check if your local js directory has jquery.autocomplete.js file and that you have included it properly.
in my browser (firefox) the example does not work…
changing the order of the includes works!
First: include jquery
Then: include autocomplete
then it works. YMMV
It is not working for me. Not showing any error too. Please help.
Hello,
Great, it works here! But not with the HTML5 attribute “autofocus”…
thanks for the code its works fine…. but i want to know how to pass extra parameters
@Naveen – You can pass the extra parameters like this:
$('#country').autocomplete("getdata.jsp", {extraParams: {bar: 4 }} ); // This will generate url like: // getdata.jsp?q=some&bar=4Hope that helps.
Hi
I’m newbie in jQuery,
autocomplete works fine getting employee names using this code
/* employeeData.jsp */
empV=empItt.empAutoComplete(); Iterator it=empV.iterator(); while (it.hasNext()){ String myId=(String)it.next(); String myName=(String)it.next(); out.write(myName+"\n"); }/* main page */
jQuery(function(){ $("#country").autocomplete("employeeData.jsp"); });But I failed to get the employee id in hidden field, Please what the method I should use
to get the id in hidden field
Thanks in advance
@Rahman: I assume you have a requirement where user can select Employee name in autocomplete box and the selected employee’s emp_id should be stored in a hidden field.
To do this consider following code snippet:
var data = [ {emp_name:'Employee A', emp_id:'121'}, {emp_name:'Employee B', emp_id: '345'} ]; $("...").autocomplete(data, { formatItem: function(item) { return item.emp_name; } }).result(function(event, item) { $('#hidden_field').val(item.emp_id); });Here in above code, your jsp generates output in JSon format [ {emp_name:'Employee A', emp_id:'121'}, {emp_name:'Employee B', emp_id: '345'} ]. Both emp_name and emp_id are present in the json output.
Also the hidden field id is “hidden_field” whose value we set in result() method.
Hope this helps you have solves your problem.
Thank you for your quick reply
Problem solved when I wrote the piece of code below where empIdTT is a hidden field
$("#country").result(function(event, data, formatted) { if (data) $("#empIdTT").val(data[1]); });thanks for giving this example ….its realy so good try it once
Thanks Kishore
Hi …Thanks alot ..This does work cool …
Could u please suggest how to generate an action when the user clicks on any suggestion disaplyed ..
say , For example : In the Example you illustrated i need to direct the user to ‘www.abc.com’ when he/she selects ‘Angola’ .
thanks a lot
Thankss a lot