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. 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; } }
Code language: Java (java)
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>
Code language: HTML, XML (xml)
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");
Code language: JavaScript (javascript)
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); } %>
Code language: Java (java)
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
Code language: CSS (css)
Execute the code in eclipse and you will get the desired output:

Download Source Code

Java_JQuery_Autocomplete_example.war (11 KB)

View Comments

  • 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

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

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

  • 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");

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

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

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

  • 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

Share
Published by
Viral Patel
Tags: autocomplete Java JQuery jquery plugin JSP

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago