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.

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.

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 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:
autocomplete-java-jquery

Download Source Code

Java_JQuery_Autocomplete_example.war (11 KB)



218 Comments

  • Kenneth 19 November, 2012, 18:30

    Really nice works like a charm. Thank you

  • mallii 22 November, 2012, 10:01

    this is
    very good example

    please give example on struts2 hibernate

  • Sachin 26 November, 2012, 10:00

    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.

  • jatin 17 December, 2012, 17:34

    Where from this “q” comes? As there is no parameter whose name is q in index.jsp
    String query = request.getParameter(“q”);

    • ezfzgf 26 March, 2013, 22:25

      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;
      	};
      
      • x person 17 May, 2013, 14:49

        really nice example understand easily for freshers:)

  • shiv 20 December, 2012, 17:29

    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)

  • Thomas 20 December, 2012, 21:37

    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…

    • Deepika 26 June, 2013, 10:58

      Hi Thomas,
      If you use firebug to check the url which is generated after you enter the alphabet in text box, you can see that at the end of that url parameter is being added. Like if you type ‘w’ then at the end of generated url you get ?q=”w”. So, if we do request.getParameter(“q”) on getData.jsp then you get the alphabet which is entered on index.jsp on getData.jsp. Hope it helps.

  • samydurai 4 January, 2013, 12:37

    above example is very nice and super.

  • Ashwin kumar 11 January, 2013, 15:33

    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

    Declare @LoggedInUserID int = 2;
    
    With User_Cte as
    (
    	Select UserID, UserName, DesigID, ReportingTo   
    	from Users 
    	where UserID = @LoggedInUserID
    	Union ALL
    	Select t2.UserID, t2.UserName, t2.DesigID, t2.ReportingTo   
    	from Users t2
    	Inner join User_Cte as uc on uc.UserID = t2.ReportingTo   
    ) 

    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.

  • Basappayya 22 March, 2013, 12:14

    Thanks a lot, Very nice example.

  • Vishwnath M Patil 30 March, 2013, 18:07

    super example……..

  • rahul srivastava 2 April, 2013, 11:33

    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……..

  • Sonia 3 April, 2013, 1:00

    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

  • Rahul Srivastava 3 April, 2013, 15:50

    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

  • Wicharn 6 April, 2013, 11:03

    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?

  • Pavan 7 April, 2013, 19:35

    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”);

  • Amir 15 May, 2013, 6:59

    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.”

  • Sudhakar 31 May, 2013, 13:28

    All topics are really wonderful , Thanks for your valuable post!!

  • Deepika 27 June, 2013, 14:43

    Hi Viral,
    I got one problem now. I have used this example as reference in another project. In that project I am providing auto complete in the similar way but when I type an alphabet in text box I am getting the items from my list after some blank lines. I have checked in my database also & there are no empty records in database. Any one having any idea why this issue is coming please let me know.

    Thanks in advance.

  • Omkar Deshmukh 11 July, 2013, 11:08

    hi team,

    i am requesting one parameter through request.getParameter(); in my servlet from on jsp. what will happend if i dont pass values to this parameter from that jsp.

    will it cause Bad Request exception?

    kindly give me the solution for this if yes.

  • Anonymous 17 July, 2013, 6:13

    Hi VP,

    Nice Example and working fine. But Could you please explain how request.getParameter(“q”); gets populated?

  • anit 1 August, 2013, 17:13

    can someone help me out
    i am getting below meessage when i try to run above example

    http://localhost:8080/AutocompleteExample/

    type Status report

    message /AutocompleteExample/

    description The requested resource (/AutocompleteExample/) is not available.

  • Shakti Ranjan 24 August, 2013, 11:45

    hello sir,

    this code is working fine,
    this website helped me and my friends most.

    thnxxxx

  • Navs 30 August, 2013, 12:25

    Thansk Virat!! nice example

  • Blasko 2 September, 2013, 6:17

    Pls little help, I don’t know how to get this work with cyrillic letters… Thanks in advance

  • viju 4 September, 2013, 12:38

    Hi,
    Thanks for the tutorial. I was looking for some source which will get my work done really fast. After reading this tutorial, it appeared the parameter “q” seems to be haunting everyone. As suggested by Deepika, it is passed as a parameter by getData.jsp (host/app/getData.jsp?q=”in” ). It contains the letters you type in the country box.
    The “q” can be traced in jquery.autocomplete.js in the function requestData(q).

     function requestData(q) {
    		if (!options.matchCase) q = q.toLowerCase();
    		var data = options.cacheLength ? loadFromCache(q) : null; 
                   : :
    

    JQuery uses this to pass the content of the selector $(#country) to autocomplete() ‘s requestData() function and then it is passed to the getData.jsp which is used above in the code. Hope this helps everyone who have been wondering where q comes from. Cheers! :).

  • Poonam 19 September, 2013, 15:54

    Hey unfortunately it’s not working in my case :(..suggestions are not being shown after typing letter(s)..wat can b d possible reason(s)??

    • jayant 23 September, 2013, 15:37

      Thanks Viral, Its working for me…

      @Poonam .. r u using db for fetching values?

  • pathak nisarg 26 October, 2013, 23:36

    Hey unfortunately it’s not working in my case .suggestions are not being shown after typing letter(s)..what can b d possible reason?

  • Waseem Akram 29 October, 2013, 12:54

    Hi , i m trying to generate autocomplete feature for dynamically generated text boxes
    can u please help me out in attaining this feature

    thanks in advance

  • parth 2 November, 2013, 14:34

    thank you very much. Nice work!

  • Shruthi 5 November, 2013, 17:17

    Hey great tutorial !!!! Keep going !

  • Arun 30 December, 2013, 18:21

    Hi sir your code is working fine.. But i have a problem in date picker..
    In 1.3.2 js date picker not working but if i attach 1.9.2 js ,date picker is working fine but auto complete is not working.. Please help me sir….

  • Raghu 30 December, 2013, 23:49

    Hi Viral,

    Can you please help me to integrate autocomplete feature with h:selectonemenu ?

    <h:selectOneMenu id=”location_id” value=”#{DataUpdateBean.Location}”>
    <f:selectItem itemValue=”” itemLabel=”” />
    <f:selectItems value=”#{DataUpdateBean.LocationList}” />
    </h:selectOneMenu>
    
    

    Thanks,
    Raghu

  • Ozan 28 February, 2014, 21:06

    Hi Viral great exampe:

    How can I set min character before bring the suggestions ?

    Thank you !

    • Anny 4 October, 2014, 12:09

      Hi..I am getting one problem for the autocomplete example.I have added database connection in DummyDB.java file.In tomcat its working fine,but in JBoss its throwing Null Pointer Exception. I am using struts 1.2 framework and SQL server 2005.Please help me,its urgent..Thanks in advance.

  • saurabh 25 March, 2014, 13:20

    Hi , How we can use jquery.autocomplete.js library in angularjs ? could you give any example

  • Wally 10 April, 2014, 2:04

    Looks nice and everything is working for me… The only question I have is: Is there any way not to reference http://www.google.com/jsapi? I am not allowed use out side references.

    Thanks in advance…

  • Kirti Batra 23 April, 2014, 12:56

    Your Code helps alot !

  • Priyanka 6 June, 2014, 9:44

    Hi VIral,

    Very clean tutorial. I was looking for just the same and it worked smooth.Thanks a lot.
    When i tried the same script fr numbers, it is not working (eg. job Ids)
    Please tell me how to make it work for numbers.
    Thanks in advance.

  • Priyanka 6 June, 2014, 9:54

    Sorry Viral,
    Its working for numbers as well.
    Thansk a lot.

  • sadhvi 3 July, 2014, 21:20

    Hi thank you for such a wonderful tutorial,
    I have a question i am creating Timesheet app using JSP and servlets. And i am trying to add all week 1 values and place them in totalweek1. i am using jquery but for some reason i am not able to acheive the reuslt

    PLease help

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *