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.
I’ve tested it with Struts action class instead of calling jsp. It works fine. Simply pass the struts action class url. As stated in API, jquery would append parameter ‘q’ containing the current search value.
Thank you all.
Hi Viral,
Thanks for your great help. I have used your code and it is working successfully.
I am facing a problem like i am using onblur function of JSP on field for which i am using your script (autocomplete). In such case when i use up-down arrow of keyboard for selecting value (autocomplete list box) it works perfect but wheni use mouse arrow only the value which is written in text field passes to onblur function (not the complete value which i select from list box arising for autocomplete). please help for such case.
Hi Viral, I created a functionality of dynamic adding rows
using one of your other tutorial that uses for dynamic row adding in a table
var row = table.insertRow(rowCount);
so, I created a sample row of several textboxes and the add row function is working fine.
The question is how to trigger autocomplete for each of the row in one of the column of text boxes.
The id of the text box for the first row that I modeled was “itemNumber”.
Now for the rest of the rows i do not know what and how to trigger the autocomplete?
$(document).ready(function(){
$(“#itemNumber”).autocomplete(“someURL”);
});
This works for the first row’s text box only…
Could you please send how to get and pass the dynamic rowIDs and call autocomplete
a very good tutorial, which came to me in handy, i would like to know if we can change the parameter q to our desired one, if so where should i change the jquery script.
Any ideas?
Nice piece. I tried to run applicaiton but ended up with the following
‘jQuery’ is undefined
Any suggestions?
Many thanks
Hi Viral,
excellent work….!
Plz i need to retrieve data from mysql database can you help me with that.
i’m new to jsp.
Can you provide an example where the autocomplete works with a primary key and value combination. Only the value must be shown, but the primary key is returned to the web page when the value is chosen.
Thanks
very nice example,i appreciate it ,but can u just tell me where is the callback function?
hi sorry but
i find this error for your application
An error occurred at line: 8 in the generated java file
Only a type can be imported. net.viralpatel.autocomplete.DummyDB resolves to a package
Une erreur s’est produite à la ligne: 5 dans le fichier jsp: /getdata.jsp
DummyDB cannot be resolved to a type
2:
3:
4: <%
5: DummyDB db = new DummyDB();
6:
7: String query = request.getParameter("q");
8:
hi you are here can you help me !!!!
Nicework Viral, in my code, i have populated part description and I need to get the part num also for the same, how do I do it?
Thans for yr code , Nicework Viral, in my code, i have populated part description and I need to get the part num also for the same, how do I do it?
hi Viral
thank for your help
but i have a problem as same as @Vishnu had written earlier posts could u help me solve it?
best regards
hola querido amigo,buen dia. quisiera porfavor que me expliques la manera de hacer todo eso con acceso a base de datos mysql,soy principiante en eso.te agradezco mucho por tu valiosa ayuda. oscar
hello dear friend, good day. please would you tell me how to do all that with access to mysql database, I am beginner in eso.te thank very much for your valuable help. oscar
Hi Viral
Thanks for sharing such a excellent tutorial . It helped me a lot.
Had a small doubt/problem while implementation , The code is working fine the issue is while the data is retrieved from DataBase and displayed in the list I get extra rows as well as extra value “”http://www.w3.org/TR/html4/loose.dtd” which is not there in the DB .
Can you please guide me thru the same .
Thanks in advance.
Hi Viral,
Nice tutorial. But for some reason it’s not working from. Looks like it is not calling getdata.jsp. I am using jquery-1.4.2.min.js do you think that is causing the problem?
Thanks in advance!!
i don’t know much about how to implement this and how it works… could someone help me understand, my general understanding is quite gd, just not when it come to java. I’m using PHP, Mysql and Apache. i have an idea of what needs to be done just I know these things are finiky and if someone could walk me though the process i would be grateful
Hi Viral,
This is a nice article and helped in understanding autocomplete functionality.
I have a scenario that you can advise on.
I am searching users from the database by their name and once the user is selected from the autocomplete dropdown then the user’s name, id and email address are need to be saved upon user clicking the Save button.
My question is somewhat related to Sreenivas’s question but he didn’t get any answer on that.
Thanks in advance
How to implement the same in JSF?
Hi Viral,
Great piece of code. Works perfectly.
I have used this with a DB and want to disable caching so that updates are shown directly from DB as they might be changing.
Presently, the function to retrieve data from DB is only called once i.e. only the first one for every literal/query. I want it to happen everytime even when the same query is entered.
I tried noCache:true option and even tried removing all cache involving functions from the js but none of it works. Still the DB is queried only once for the same query.
Kindly help. Thanks in advance.
How to set limit in display record? pls describe syntax for below code
Hello sir,
i access record with around one lacs database in jsp struts2, in dojo it become very loaded so,i used jquery autocompleter ,thanxs but i want to limit it in showing record.pls help me
it is urgent
my code is below.
$(“#country”).autocomplete(“webpages/getdata.jsp”);
Hi Brajesh,
You may use this:
$(“#country”).autocomplete(“webpages/getdata.jsp”,{maxItemsToShow : 10});
@Rajat
Thank you very much for the help i will try this.
I m facing problem in this example. when i type anything in country textbox. It is not hitting the getdata.jsp. find no error also. please help me
Hi, Viral, thanks for the tut, but I don’t am not able to work with this. I have made some changes, like to the java file name and instead of using a static one I have used data from my database. When I am pressing a key on the index page, nothing is happening. I have also changed the text field name to security and correspondingly have used $(“#security.”).autocomplete(“getdata.jsp”).
I have added the js and css file to the location u asked us to keep them at.I have no clue why it is not working. Do I have to download a plugin ot something?
Hi Viral Patel Thanks
Iam using IE7 this auto complete script is not supporting in my browser .is it possible to do without using script code . we have some difficult to analyse script .so any simple java code is available? iam using struts2 tag but its not working it showing drowdown only. pls help me any simple way to implementation using java,jsp.
if u have any idea of struts2 tags is easy to me pls help me…………………….
How to call an action instead of getdata.jsp
Hi Viral,
Such a nice article. Thanks a lot. Keep it up.
I just want to know how can I call Ajax to retrieve data.
Regards,
Brij
Hi Viral,
Thanks for nice example on autcomplete functionality. For me code works fine in IE browser but same is not working in mozilla. When i enter a character in the text field I am getting “The ‘charCode’ property of a keydown event should not be used. The value is meaningless.’ warning message. Could you please suggest me how to resolve this issue?
I am working on Strus1.0, can u pls send the code to implement autocomplete in jsp
Hi..I am using struts2 and jsp for my project.I am able retrieve data from database onto the action class but I want to get the same onto the jsp page.I am using Mysql and eclipse IDE.Kindly help.Thanks in advance
Thanks for the information.
but when i deployed the war file in eclipse and i then run it on Jboss from index.jsp
it show me index file with a text box.
but when i press ‘A’ or any alphabet it does gives any information regarding country name’s starting with ‘A’ .
in eclipse it show following message
at java.lang.Thread.run(Unknown Source)
Hi Viral,
I am just beginning to learn autocomplete and jquery.
1. Can we use struts2 and jquery jar lib to accomplish this?
2. Can u point out some exam[ple?
Aditya
Hi Viral,
Such a nice article. Thanks a lot. Keep it up.
http://javamsmq.codeplex.com/
Hi Viral,
I am having problem during mouse click. I am not getting any data when I select on the dropdown using mouse click but it works fine using arrow keys. Please help. Thanks!
Hi Viral
Very Nice Plugin
Nice tutorial, but I have some problems here, I just have Copied and Pasted all things but when I type a letter nothing happens. I wonder why?
Good evening,
First I would like to congratulate the tutorial because you saved my life.
I am having trouble connecting using this example in a database.
I have a table with names of countries worldwide. Where should I put my query so I can get the countries in this table?
Great little tutorial. Easy to follow and understand for a java noob like myself.
Hi…can any one plz help me in integrating it with Struts2 application…what return type is expected in action class….
Thanks….
Hi
any idea how this work like GOOGLE search ,like name is “Hello” if user type “ello” it should display Hello in list
Hey,
This is a nice tutorial. I would add a note of caution however. Doing Java code in JSP is good for a quick demo, but is not a good long term approach. It is not easily unit testable (unless with Selenium) and is not compiled until runtime.
I am currently using DWR with Jquery autocomplete for this and it works perfect.
http://directwebremoting.org
Thanks
Can the returned list also be a String like:
String personList = null;
List ldapUsers = ldap.getUids();
for (int i=0;i<ldapUsers.size();i++) {
personList+=ldapUsers.get(i).getUid()+"\n";
}
Hi
This is very useful also business peoples like me who read from net can easily understand this.Htas of Viralpatel.
Viral this is good code for single textbox.But if i had 4 textbox and if i select a name from firsttext box i want to get datas for this from DB in balance three textbox.Is it possible.If so please help me.
yayaya, me also not working….
im not sure why it wasn’t worked.
Even tough mysql command already correct using LIKE statements,
and the jsp page already corrected to println (line by line).
Seems the plugin is not fully customized with jquery 1.4.2 version that i’m currently using on right now. Thus, if there’s any updates let me know ya?
Thanks dude!
Hi Viral,
Does the autocomplete feature work only in a dynamic web project in eclipse?
With Regard’s
Saranya Jayaram
I run this code in eclipse, it’s not working at all.
Nice. But only problem here is the machine needs to be in internet
Is there any way to resolve it?