Autocomplete with jQuery and Servlet

Autocomplete with jQuery and Servlet: Full Guide (2026)

Autocomplete with jQuery and Servlet: Full Working Guide

An autocomplete box is one of the small features that makes an app feel polished. Type a few letters, and matching suggestions appear instantly below the input. In this guide, I will show you how to build Autocomplete with jQuery and Servlet from scratch — the HTML page, the JavaScript with AJAX, the Java Servlet that returns JSON, and the Maven setup. By the end, you will have a working example you can drop into any Java web project.

What is autocomplete with jQuery and Servlet?

Autocomplete is a UI feature where the input box suggests possible values as the user types. Think of the search bar in Google or the destination field in a travel app. The user types "ind", and "India" appears below.

With jQuery and a Servlet, the flow works like this:

  1. The user types into an input box on the HTML page
  2. jQuery UI's autocomplete widget sends the typed text to the Servlet via AJAX
  3. The Servlet filters its data list based on the typed text
  4. The Servlet converts the result to JSON using Gson
  5. The Servlet writes the JSON back to the browser
  6. jQuery UI shows the JSON as a dropdown list under the input box

Each keystroke triggers a request, but jQuery UI throttles them so the server is not flooded. That keeps the UI responsive while the data stays fresh.

The result is smooth, instant suggestions without any page reload.

What the output looks like

Here is what you get at the end:

  • A simple page with one input box labeled "Country"
  • As you type, a dropdown appears below the box showing matching countries
  • Click a suggestion to fill the input box with it

Output screen — autocomplete in action

Autocomplete with jQuery and Servlet output screen showing country suggestions dropdown

The data set is hardcoded in the Servlet for simplicity — 10 countries including India, America, Russia, France, Spain, and more. In a real app you would replace this with a database query, but the structure stays the same.

Project structure overview

The project has two main parts — the front-end files and the Java back-end.

HtmlDemo
├── WebContent
│   ├── index.html
│   └── js
│       └── my.js
├── src
│   └── deepsingh44.blogspot.com
│       ├── controller
│       │   └── CountryController.java
│       └── model
│           └── Country.java
└── pom.xml

The WebContent folder holds the HTML, CSS, and JavaScript files. The src folder holds the Java classes. The pom.xml at the root defines the Maven build and dependencies.

index.html — the front-end page

The HTML page is short. It loads the jQuery UI CSS, the jQuery core library, jQuery UI, and our custom JavaScript file.

<html>

<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="js/my.js"></script>
</head>

<body>

    <div class="ui-widget">
        Country: <input id="country" placeholder="Enter Country Name...">
    </div>

</body>

</html>

Let's look at each line:

  • jquery-ui.css — provides the default styling for the autocomplete dropdown
  • jquery-1.12.4.js — the jQuery core library
  • jquery-ui.js — provides the autocomplete widget itself
  • my.js — our custom JavaScript that wires everything up

The div with class ui-widget applies the default jQuery UI theme to the input box, so it matches the dropdown that appears below it. The input has id country — that is how our JavaScript finds it.

The versions here are old but stable. They work with any modern browser. If you want newer versions, just change the version numbers in the CDN URLs.

my.js — the AJAX autocomplete code

This is the JavaScript that turns the plain input box into an autocomplete field.

$(document).ready(function() {
    $(function() {
        $("#country").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "country",
                    type: "POST",
                    data: { term: request.term },

                    dataType: "json",

                    success: function(data) {
                        response(data);
                    }
                });
            }
        });
    });
});

Here is what each part does:

$(document).ready()

Waits until the page is fully loaded before running the code. This ensures the input element exists when we try to attach the autocomplete widget.

$("#country").autocomplete({...})

Attaches the jQuery UI autocomplete widget to the input with id country.

source: function(request, response)

The source option tells the widget where to get suggestions. By default it expects a static array, but we can pass a function that fetches from the server. The request object has request.term — the text the user typed. The response callback is what we call with the results.

$.ajax({...})

Makes the AJAX call to the server. The key options:

  • url: "country" — the servlet URL. Matches @WebServlet("/country") in the Java class.
  • type: "POST" — sends a POST request, which is a good default for sending search terms
  • data: { term: request.term } — sends the typed text as a parameter named term
  • dataType: "json" — tells jQuery to expect JSON back and parse it automatically
  • success: function(data) — when the response arrives, pass it to response(data) so the widget can show it

The data here is a JavaScript array like ["India", "Spain"]. jQuery UI autocomplete knows how to display a plain array of strings — it just shows each one as a suggestion.

Country.java — the data model

The Country class is a simple data holder. It has a name field with a getter and setter.

package deepsingh44.blogspot.com.model;

public class Country {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

That is the whole class. It represents one country in the data list. Keeping it simple like this is fine — a data holder should not have logic. In a real app, you might have more fields like code, population, or continent. But for autocomplete, all we need is a name.

CountryController.java — the Servlet

This is the heart of the back-end. It handles both GET and POST requests, builds the data list, filters it by the search term, and returns JSON.

package deepsingh44.blogspot.com.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import deepsingh44.blogspot.com.model.Country;

@WebServlet("/country")
public class CountryController extends HttpServlet {

    List<Country> list = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json");

        dataSet();

        String name = req.getParameter("term");
        List<String> ll = search(name);

        Gson g = new Gson();

        String jsondata = g.toJson(ll);
        System.out.println(jsondata);
        resp.getWriter().write(jsondata);

    }

    private List<String> search(String name) {
        List<String> names = new ArrayList<>();
        for (Country item : list) {
            if (item.getName().toLowerCase().startsWith(name)) {
                names.add(item.getName());
            }
        }
        return names;
    }

    private void dataSet() {
        list = new ArrayList<>();
        Country c1 = new Country();
        c1.setName("India");
        Country c2 = new Country();
        c2.setName("America");
        Country c3 = new Country();
        c3.setName("Russia");
        Country c4 = new Country();
        c4.setName("France");
        Country c5 = new Country();
        c5.setName("South Africa");
        Country c6 = new Country();
        c6.setName("New Zealand");
        Country c7 = new Country();
        c7.setName("Spain");
        Country c8 = new Country();
        c8.setName("Argentina");
        Country c9 = new Country();
        c9.setName("Malaysia");
        Country c10 = new Country();
        c10.setName("Afghanistan");
        list.add(c1);
        list.add(c2);
        list.add(c3);
        list.add(c4);
        list.add(c5);
        list.add(c6);
        list.add(c7);
        list.add(c8);
        list.add(c9);
        list.add(c10);
    }

}

Let's walk through it:

@WebServlet("/country")

The annotation maps this Servlet to the URL /country. When the browser posts to country, this Servlet runs.

doGet

Delegates to doPost. That means the Servlet accepts either method. Useful if you want to test it by typing the URL in a browser.

doPost

The main method. It does four things:

  1. Sets the response content type to application/json so the browser knows it is JSON
  2. Calls dataSet() to fill the list (in a real app, you would query a database instead)
  3. Reads the term parameter, filters the list, and builds a list of matching names
  4. Converts the list to JSON with Gson and writes it to the response

search

Loops through the country list and checks if each name starts with the search term. Uses toLowerCase() on both sides so the search is case-insensitive — typing "ind" or "IND" matches "India" the same way.

dataSet

Builds a list of ten Country objects with hardcoded names. In a real application you would replace this with a JDBC query or a call to a service. For learning, the hardcoded list is enough.

Note: we call dataSet() on every request, which rebuilds the list each time. That is fine for a demo. In production, you would load the data once and cache it, or query the database only for what matches.

The System.out.println(jsondata) line is useful for debugging — it prints the JSON to the server console so you can see exactly what is being sent back.

pom.xml — the Maven setup

The pom.xml defines the project as a WAR (web archive), sets Java 8 as the source/target, and adds the Gson dependency.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>HtmlDemo</groupId>
  <artifactId>HtmlDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
  <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>
  
  </dependencies>

</project>

The key parts:

  • packaging: war — tells Maven to build a WAR file, which is what you deploy to a Servlet container like Tomcat
  • maven-compiler-plugin — configures Java 8 as the source and target version
  • maven-war-plugin — tells Maven to treat WebContent as the web root instead of the default src/main/webapp
  • gson dependency — pulls in the Gson library for JSON conversion

Once you have this, run mvn clean package and deploy the generated WAR file to Tomcat. The Servlet will be available at http://localhost:8080/HtmlDemo/country and the HTML page at http://localhost:8080/HtmlDemo/index.html.

Common questions

What is autocomplete with jQuery and Servlet?

Autocomplete with jQuery and Servlet is a pattern where jQuery UI's autocomplete widget sends the typed text to a Servlet via AJAX, the Servlet queries data and returns matching results as JSON, and the widget shows them in a dropdown list under the input box.

Which jQuery libraries are needed for autocomplete?

You need the jQuery core library and jQuery UI. The jQuery UI CSS file provides the dropdown styling, and jquery-ui.js provides the autocomplete widget itself.

Why use Gson in the Servlet?

Gson converts Java objects into JSON strings and back. In an autocomplete Servlet, you build a List of matching names, then use Gson to turn that list into a JSON array that jQuery can parse directly.

What is the term parameter in autocomplete?

The term parameter is the text the user has typed into the input box. jQuery UI sends it automatically to the configured URL as a request parameter named term. The Servlet reads it with req.getParameter("term").

How do I filter results in the Servlet?

Loop through your data list and check if each name starts with the term using startsWith. If it matches, add it to a result list. Send that list back as JSON.

What Maven dependency is required for Gson?

Add com.google.code.gson:gson:2.8.6 to your pom.xml dependencies. Any recent version of Gson will work.

Where to go next

You now have a complete, working autocomplete with jQuery and Servlet. You know the HTML setup, the JavaScript AJAX call, the Servlet's doPost logic, and the Maven configuration.

If you remember only one thing, remember this: jQuery UI sends the typed text as term. The Servlet filters its data, converts to JSON with Gson, and writes it back. jQuery UI shows the result as a dropdown.

The real learning happens when you run this in a Servlet container like Tomcat. Deploy the WAR, open the page, and type "ind" — you should see "India" appear. Change the data set, add more countries, or switch to a database query. That is how the pattern becomes second nature.

If this helped, bookmark it. Next, try replacing the hardcoded data with a JDBC query, or make the autocomplete case-insensitive with contains() instead of startsWith(). Both are natural next steps.

No comments: