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)



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

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

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]