Tutorial: Create Autocomplete feature with Java – JSP / jQuery

      

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.

eclipse dynamic web project

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.

new-package-autocomplete-dummydb

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.

autocomplete-jquery-plugin-jsp

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 src="js/jquery.autocomplete.js"></script>
	<script type="text/javascript"
			src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.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:
autocomplete-java-jquery

Download WAR file with Source code. (11 kb, war file)


Facebook  Twitter      Stumbleupon  Delicious
  

56 Comments on “Tutorial: Create Autocomplete feature with Java – JSP / jQuery”

  • Siddhartha wrote on 18 June, 2009, 15:29

    Hello,
    This is really a nice piece of code and easy to use, but in my case when i implemented the same piece of code with my JSP its behaviour is changed now when we I open the JSP it showing alert message that \"Internet Explorer cannot open the site\" then my site name and in last \"Operation aborted\".
    I am using IE7. Please help me on this.

    Thnx

  • Viral Patel wrote on 18 June, 2009, 15:40

    Hi Siddhartha,
    I am not sure if this has something to do with browser. I have used jQuery and a plugin which generally are browser independent. I am not about your issue. Can you try running your code in some different browser?

    I have not tested this code in IE 7 but I assume it should work. Also check your browsers security settings. In my code, I am trying to include jquery script from google scripts webisite: http://www.google.com/jsapi. You may want to change this piece of code and include your local jQuery javascript.

  • Siddhartha wrote on 18 June, 2009, 16:27

    Hello Viral,
    Thnx for your quick reply, I ran the war file which is available on this site, it is running fine. But when i use the same code snippet, some error comes and doesn’t allow to open my site.
    Anysways, how can I implement my own jQuery javascript.
    please guide me.

  • Viral Patel wrote on 18 June, 2009, 17:01

    You can download jQuery javascript file at http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.1.min.js and include it in your HTML file with <script> tag:
    <script src=”jquery-1.3.1.min.js”></script>

    Hope this will work for you.

  • Siddhartha wrote on 19 June, 2009, 9:05

    Thnx viral for the support, I have done what u have written but now it is not finding the google.load() method and if I remove this no error comes but no suggestions come.
    What should I use instead of google.load . Please see my code below and guide me what changes I need to do,

    google.load(“jquery”, “1″);

    input {
    font-size: 120%;
    }

    Country

    $(“#country”).autocomplete(“getdata.jsp”);

  • Viral Patel wrote on 19 June, 2009, 13:28

    Try running following code and see if it is running fine. Note that the javascript file needs to be in same directory as your html file as we have included the js directly.

    
    <!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 src="jquery-1.3.1.min.js"></script>
    	<script>
    		$(document).ready(function(){
    			$("#country").autocomplete("getdata.jsp");
    		})
    	</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"/>
    
    </body>
    </html>
    
  • M.Santosh wrote on 16 July, 2009, 16:59

    hi…
    i have used your countries search code but i have a requirement that when i press key down it should place that value in text field,please provide the solution its urgent.

    Thanks and Regards
    Santosh

  • Dhurai wrote on 4 August, 2009, 19:27

    Hi,
    I run your war file successfully. But if I change the data string in DummyDB, I am not getting the output.. But U have specified that we can add a select query in DummyDB.java.
    Whether the data string in DummyDB.java is changable or not? Please reply.

  • Viral Patel wrote on 4 August, 2009, 20:15

    Yes Dhurai,
    The data in DummyDB.java is just for the reference and can be changed. You may also implement your getData(String query) method that returns the matched data. This class is just to demonstrate the functionality. In reality the data will come from database.

  • Andrew Krenitz wrote on 4 August, 2009, 22:16

    Hi,
    I am having trouble understanding
    String query = request.getParameter(“q”);
    How did name the parameter (q) ? Also, how can I add other parameters to send to the servlet?

    Thanks

    Andy

  • Viral Patel wrote on 4 August, 2009, 22:45

    Hi Andrew, If you noticed, we have invoked the jquery plugin by

    $("#country").autocomplete("getdata.jsp");

    Thus, this plugin will call getdata.jsp using ajax, whenever user presses a key in textbox and pass the parameter using q as the name of parameter in request. Thus you can get the string entered by user in your script file (in this case getdata.jsp) using q request parameter.

    If you want to pass some other argument to the script you do so as follow:

    $("#country").autocomplete("getdata.jsp?xyz=123");

    In short you have to pass the parameter to script file while calling plugin function.

  • Andrew Krenitz wrote on 5 August, 2009, 2:28

    Hi Viral,

    Thanks for your response.

    As I understand, “q” is the default parameter passed? All other parameters passed are named in the url string?

    Do you recommend using a servlet or using a jsp to produce output? Currently, I’ve set up a javascript version using a servlet.

    Thanks

    Andy

  • matelo wrote on 10 August, 2009, 18:18

    hello
    first, thank you for nice example, i was searching for this for a long time.
    but i need a help with my problem. i use same solutions like in this tutorial, but in my jsp i use h:inputText

    So when i want to call jquery autocomplete, id of my component is: $(“#newOrderForm:customer”).autocomplete(“getdata.jsp”);
    However, this doesn’t work. It seems that “:” in id is problem.
    Can you help me how to solve this?

  • Viral Patel wrote on 10 August, 2009, 18:50

    Hi Matelo,
    There seems to be some problem with your jquery selector code ”#newOrderForm:customer”. Try playing with this code and add some text in the DIV and see if it is working.
    $(”#newOrderForm:customer”).text(“Hello World”);

    If this works than I don’t see any problem why it should not work with autocomplete plugin code.

  • matelo wrote on 11 August, 2009, 3:53

    Yes, you are right, there is problem with selector, because when I try your example and rename “#country” with “#newOrderForm:country”, example doesn’t work.
    But i need to address my inputText component, which is inside a h:form. This form has id newOrderForm, so id of my inputText is newOrderForm:customer.
    When i don’t use jsf form, but classical html form which is used in example and my id is simple “customer”, everything works fine.

  • Raj wrote on 16 August, 2009, 11:39

    Hi Viral,
    Nice tutorial, well explained, clear instructions and images to supplement. Thank you!

  • Viral Patel wrote on 16 August, 2009, 19:24

    Hi Raj, Thanks for the comments.. Feel free to comment on any topic you like and also to subscribe for the feeds or daily articles by email.

  • Sreenivas wrote on 20 August, 2009, 18:22

    Hi Viral Patel,
    First I should thank you for such a good article on jquery autocomplete

    I have question ,my question is
    Is there a way to add name/value functionality to jquery autocomplete

    I have recently added the JQuery autocomplete plug in and have a textbox that autocompletes a list of employees. It works great and I commend the authors of the plugin.

    I think the textbox would be MUCH more useful though, when upon selecting, we can extract the StaffID (Ie. retreive the value of the selection). My code is below and you can see that I am simply adding the staff names, would be nice to associate IDs.

    Does anyone know of any way to do this?

    My JQuery:
    $(document).ready(function() {
    $(\"#tStaff\").autocomplete(\’stafflist.jsp\’);
    });
    My JSP page:

    import=\"autocomplete.TestDB\"

    String query = request.getParameter(\"q\");

    List codelist= db.getData(query);

    Iterator iterator = codelist.iterator();
    while(iterator.hasNext()) {
    String codeid= (String)iterator.next();
    String code= (String)iterator.next();
    out.println(code);
    }

    Here in the JSP code i am fetching staff names and staff id.how can i send staff id to main page.

    could you explain with a sample program how to achive the selected value ID.it would great help to me.

    Thanks

  • Sreenivas wrote on 20 August, 2009, 18:26

    Continuation for my question
    My JSP page:
    Here in the JSP code i am fetching staff names and staff id.how can i send staff id to main page.
    stafflist.jsp
    ——————-
    page import=”autocomplete. StaffDB”;

    StaffDB db = new StaffDB ();

    String query = request.getParameter(“q”);

    List Staff= db.getStaffData(query);

    Iterator iterator = countries.iterator();
    while(iterator.hasNext()) {
    String staff= (String)iterator.next();
    out.println(staff);

    could you explain with a sample program how to achive the selected value ID.it would great help to me.

    Thanks

  • eka wrote on 28 August, 2009, 9:23

    hi viral…
    nice tutorial… i have a problem when i running in the local server and request data from database…can u guide me to running this tutorial in the local server, please ..

    thanks

  • Viral Patel wrote on 28 August, 2009, 14:39

    Hi Eka, You can simply run the above example in your local server. I have used DummyDB class which simulates as if data is coming from DB. You can write your own getData method, fetch data from DB and send it back.

  • Annapurneswar wrote on 4 September, 2009, 22:31

    Hi Viral,
    I want to send parameters to my servlet .I tried the approach you have suggested in your one of the replies.But that solution is not upto the mark.
    For Ex:
    To send the parameter-value i have added the code like this
    $(“#country”).autocomplete(“servlet/dbFacade?paps=123″);
    Now when I have put alert in the makeUrl function in the js to show the url it shows like this
    servlet/dbFacade?paps=123?q=
    If you see the makeurl has a for loop which loops around extraparams.I beleiev extraparams holds the name value pairs.But I am not sure how to pass them throug the jsp page.
    Can you please suggest
    Thanks
    Annapurneswar

  • Markus wrote on 9 September, 2009, 0:34

    Hello Viral,

    nice tutorial – great job.

    One hint:
    Please update the css code of “jquery.autocomplete.css” from the link “http://www.pengoworks.com/workshop/jquery/lib/jquery.autocomplete.css”. Because right now, the “body” class is missing (but it`s available in the war file).

    Best regards,
    Markus

  • Vishal Malavia wrote on 16 September, 2009, 18:35

    Hello Viral ,
    First of all thanx for posting such a nice tutorial…
    i have a problem i want to display data in the textfield only after the user enters the first three charachters in the textfield as my string contains some 17000 words.
    i am not getting where to exactly change in the autocomplete .js it would beb really nice if you could help me out with this

    Thanx
    Vishal

  • Viral Patel wrote on 16 September, 2009, 19:15

    Hi Vishal, Ideally for such requirement, the code change should be done in autocomplete javascript, but as it is a plugin, we avoid any project specific change in such generic frameworks. What you can do is you can change the Java code or the server side script code that is getting called (in our case getdata.jsp). While retrieving the query, you can neglect the call if the query is less then three characters:

    	String query = request.getParameter("q");
    	if(q!=null && q.length() < 3) {
    		return;
    	}
    
  • Vishal Malavia wrote on 17 September, 2009, 16:24

    Hello Viral ,
    thanx for your prompt reply …
    but the way u suggested didnt work out properly so i just made a change in autocomplete js
    as follows in the function onChange() i just changed the if clause as follows and it is working fine now
    if (v == prev || v.length <= 2) return;
    prev = v;

    Thanx

  • dharmendra wrote on 29 September, 2009, 18:15

    Hi
    This code is very useful to me but I an not able to download
    the source code from this site . plz correct the link for download.

    Thanks
    Dharmendra

  • vikram wrote on 21 October, 2009, 11:28

    Hello Sir,

    Even i faced the same issues as Siddharth did reg IE …made changes … but still the functionality is not working fine .. can u pls suggest

  • Anindita Banik wrote on 22 October, 2009, 13:52

    Too good.

  • Name (required) wrote on 12 November, 2009, 14:22

    Works nicely, but copy-pasting the code is pain in the ass since you manually have to delete the line numbers. Also, why is mail required to post a comment?

  • Viral Patel wrote on 12 November, 2009, 14:35

    Hi,
    You may want to use Copy option in the code box. Just hover your mouse on code you copy and select Copy option from right side.

    Email is mandatory to check the spam :)

  • Sergio wrote on 13 November, 2009, 3:32

    Great job! Keep going!
    @Vishal Malavia: in the autocomplete plugin there is a predefined set of options, and for your case this might work: $(”#country”).autocomplete(”getData.jsp″,{minChars: 3});

  • Sergio wrote on 13 November, 2009, 3:37

    and this should work for extra parameters:

    $(”#country”).autocomplete(”getData.jsp″,{extraParams:{xzy:’something’}});

  • Mohit wrote on 17 November, 2009, 18:22

    Hi Viral,
    Very nice example.I have tried in my example. It is working fine but once i submit the form then it does not work…mean at first time when my html opens it works fine but after submitting the form it is not working…i think the script is not loading at second time. is it?

  • Tapan wrote on 18 November, 2009, 7:08
    		$(document).ready(function(){
    			$("#country").autocomplete("getdata.jsp");
    		})
    

    i am getting object expected at this point.

  • Mohit wrote on 18 November, 2009, 14:52

    Hi Viral,
    After submitting the form, I’m loading the same page and then the script is not working….when i load the page first time at that time it works fine but after wards it does not work…pls help.

  • Mohit wrote on 18 November, 2009, 15:56

    Hi Viral,
    Yes, it is working fine. Actually path of .js file was wrong in my case..
    Thanks …

  • Mohit wrote on 18 November, 2009, 15:58

    Hi Viral,
    path of java script file was wrong in my example….now it is working fine…thanks..

  • Viral Patel wrote on 18 November, 2009, 22:56

    @Mohit: Nice to see that your error got resolved! Hope you liked the article.

  • Viral Patel wrote on 18 November, 2009, 22:59

    @Tapan: Check if the JavaScript library is properly included in your HTML page. This error will come only if the JS library is not properly included.

  • Tapan wrote on 19 November, 2009, 9:13

    Hi Viral,

    My path is correct

    FollowUp Information

    $(document).ready(function(){
    $(“#country”).autocomplete(“getData.jsp”);
    })

    i have included the autocomplete css code in my css.
    my jsp and js are same level. what should i check. Please advice

  • JM wrote on 20 November, 2009, 11:30

    Great work Viral!
    Im unable to get the result from my jsp page
    Im calling this function on onkeyup event in my textbox but im not getting the data
    function funcResult() {
    $(“#userName”).autocomplete(“GetSearchResults.jsp”);
    }
    what could be the reason?

  • JM wrote on 21 November, 2009, 12:14

    I cant call my jsp page like ur calling..
    I have to put jQuery(document).ready(function(){}) only then my page is getting called..
    but i dont need that onready functionality..I wud like to call the page only after i start typing in my textbox..

  • dipendra sunar wrote on 29 November, 2009, 15:12

    nice piece of code.

    but having problem with the real datas from the database. if you can help plz, do.

  • Mohit wrote on 30 November, 2009, 11:18

    Hi Viral,
    I found following code in jquery.autocomplete.css file. what does it mean??

    display:none;/*sorry for IE5*/
    display/**/:block;/*sorry for IE5*/

  • Senthilkumar MKS wrote on 12 December, 2009, 11:59

    Hi Viral….I have implemented this code in my application….excellent…Thanks…

  • pawan wrote on 2 January, 2010, 17:27

    how to filter data in jsp

  • Niket Shah wrote on 29 January, 2010, 14:54

    Hey Viral,

    tNice piece of code. Everything works great but can you give some pointers if I need to use this script with Map rather then List, as I want to show the name of the employee and fetch the employee Id based on that for further processing.

    Any help on this will be great help to me… Thanks once Again….

  • Niket Shah wrote on 29 January, 2010, 17:00

    Hi Viral,

    I am not sure below issue in your code or I am doing anything wrong, Please advise on the same.

    The code works fine, but if you notice when you type any country name, the first member of the drop down is the code e.g “” and then the name of the country start with the desire functionality.

    I have deploy this code to bigger HTML and found that the complete HTML part comes as first Element and then the name of the country comes.

    Is this the same issue every one else facing? if yes, what will be the work around of this.

  • hardik wrote on 18 February, 2010, 12:11

    Hi, Viral
    Great tutorial for dummies.

    The thing which made me confused is why we need google’s load method.
    and please differentiate between
    1. http://www.google.com/jsapi
    2. jquery.autocomplete.js

    Are they providing different functionality.

    PLz rply
    Thanx in advance
    -Hardik

  • Viral Patel wrote on 18 February, 2010, 13:54

    @hardik: I have removed the old code to include jquery library from google api using load() method. Check the content of index.jsp now. Also the jquery.autocomplete.js is required. This plugin will add the autocomplete feature to our example.

  • Vishnu wrote on 25 February, 2010, 11:18

    Hi Viral….excellent work…Thanks…,
    How to call servlet url in autocomplete method instead of calling JSP .

    $(“#country”).autocomplete(“getdata.jsp”);

    Could you please give me suggestion to solve this issue.

    My sample code

    $(document).ready(function() {
    $(“#country”).autocomplete({
    url: ‘/WelcomeServlet’,
    minChars: 1,
    max: 10,
    width: 10,
    scroll: false
    }
    );
    alert(“Ready Function “);
    })

    ……………..
    In web.xml

    WelcomeServlet
    com.cog.AutoServletExample

    WelcomeServlet
    /WelcomeServlet

    It is not invoking the servlet.

    Thanks in Advance.

  • GR wrote on 2 March, 2010, 0:42

    Hi Viral….great code..Thanks,
    Your code only show cases which start with the query.
    Where should I change your code to accept all the cases which contain the query not just start with?
    Thank you so much.

  • Suresh wrote on 2 March, 2010, 8:10

    I second that question by Vishnu.

    brilliant work. keep posting more.

  • Suresh wrote on 2 March, 2010, 15:17

    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.

  • ankit wrote on 5 March, 2010, 9:21

    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.

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.