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)

Get our Articles via Email. Enter your email address.

You may also like...

221 Comments

  1. Kenneth says:

    Really nice works like a charm. Thank you

  2. mallii says:

    this is
    very good example

    please give example on struts2 hibernate

  3. Sachin says:

    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.

  4. jatin says:

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

    • ezfzgf says:

      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 says:

        really nice example understand easily for freshers:)

  5. shiv says:

    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)

  6. Thomas says:

    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 says:

      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.

  7. samydurai says:

    above example is very nice and super.

  8. Ashwin kumar says:

    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.

  9. Basappayya says:

    Thanks a lot, Very nice example.

  10. Vishwnath M Patil says:

    super example……..

  11. rahul srivastava says:

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

  12. Sonia says:

    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

  13. Rahul Srivastava says:

    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

  14. Wicharn says:

    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?

  15. Pavan says:

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

  16. Amir says:

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

  17. Sudhakar says:

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

  18. Deepika says:

    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.

  19. Omkar Deshmukh says:

    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.

  20. Anonymous says:

    Hi VP,

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

  21. anit says:

    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.

  22. Shakti Ranjan says:

    hello sir,

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

    thnxxxx

  23. Navs says:

    Thansk Virat!! nice example

  24. Blasko says:

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

  25. viju says:

    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! :).

  26. Poonam says:

    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 says:

      Thanks Viral, Its working for me…

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

  27. pathak nisarg says:

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

  28. Waseem Akram says:

    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

  29. parth says:

    thank you very much. Nice work!

  30. Shruthi says:

    Hey great tutorial !!!! Keep going !

  31. Arun says:

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

  32. Raghu says:

    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

  33. Ozan says:

    Hi Viral great exampe:

    How can I set min character before bring the suggestions ?

    Thank you !

    • Anny says:

      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.

  34. saurabh says:

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

  35. Wally says:

    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…

  36. Kirti Batra says:

    Your Code helps alot !

  37. Priyanka says:

    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.

  38. Priyanka says:

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

  39. sadhvi says:

    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

  40. Manish Aryan says:

    very nice code must go for it….

  41. Kunal says:

    Hello Viral

    It’s amezing work but how we can fatch backhand list

    like

    auto_ad_tag_options = new ArrayList();
    auto_ad_tag_options.add(1, “Kunal”);
    auto_ad_tag_options.add(2, “Jitesh”);

    In xhtml page.

Leave a Reply

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