ZetCode

Java Servlet autocomplete

last modified December 1, 2026

In this article we build an input field that suggests bug names while the user types. A servlet searches the names and returns them as JSON, and a few lines of plain JavaScript put them into an HTML <datalist>. No JavaScript library is needed.

An autocomplete field sends what the user has typed so far to the server and shows the matching values below the field. The browser already has the widget for the list, the <datalist> element, and the fetch function for the requests. The work left for us is the search servlet and the code that connects the two.

The examples use the Maven project from the Java Servlet introduction: Java 25, Jakarta Servlet 6.1, and the Jetty 12.1 Maven plugin with the /app context path. The servlets return JSON with Gson, as shown in Java Servlet JSON.

Suggestions in HTML

We start without a server. The <datalist> element holds a list of options, and an input field refers to it with the list attribute.

src/main/webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bugs</title>
</head>
<body>
    <label for="bug">Bug:</label>
    <input id="bug" list="bugs">

    <datalist id="bugs">
        <option value="Bed bug">
        <option value="Cicada">
        <option value="Hornet">
        <option value="Wolf spider">
    </datalist>
</body>
</html>

The page has one input field with four fixed suggestions.

<input id="bug" list="bugs">

The list attribute holds the id of the datalist. When the user types into the field, the browser shows the options that match the typed text and fills the field with the chosen one. The user may still type any other value; a datalist suggests values, it does not restrict them.

A static list is enough for a handful of values. For hundreds or thousands of values, we let the server do the search and send only the matching ones.

The search servlet

The bug names are stored in a text file, one name per line. The application reads the file once and searches the names in memory. The final project has the following structure.

pom.xml
src/main/
├── java/com/zetcode/
│   ├── service/
│   │   └── BugService.java
│   └── web/
│       ├── BugServlet.java
│       └── SearchServlet.java
├── resources/
│   └── bugs.txt
└── webapp/
    ├── WEB-INF/
    │   └── bug.jsp
    └── index.html
pom.xml (dependency)
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.15.0</version>
</dependency>

We add Gson to the POM of the introduction. It turns the list of names into a JSON array.

src/main/resources/bugs.txt
Assassin bug
Avondale spider
Backswimmer
Bamboo moth
Banana moth
Bed bug
Black cockroach
Blue moon butterfly
Bumble bee
Carpenter bee
Cattle tick
Cave weta
Centipede
Cicada
Cinnabar moth
Click beetle
Clothes moth
Codling moth
Earwig
Eucalyptus longhorn beetle
Field grasshopper
Garden slug
Garden soldier fly
German cockroach
German wasp
Giant dragonfly
Giraffe weevil
Grass grub
Grass looper
Green planthopper
Greenhouse spider
Gum emperor moth
Gum leaf skeletoniser
Hornet
Mealybug
Mites
Mole cricket
Monarch butterfly
Mosquito
Silverfish
Wasp
Water boatman
Winged weta
Wolf spider
Yellow admiral
Yellow jacket

The file contains 46 bug names, one per line. Files in src/main/resources end up in WEB-INF/classes, so we read them from the class path.

com/zetcode/service/BugService.java
package com.zetcode.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;

public final class BugService {

    private static final List<String> BUGS = load();

    private BugService() {
    }

    private static List<String> load() {

        try (InputStream is = BugService.class.getResourceAsStream("/bugs.txt")) {

            if (is == null) {
                throw new IllegalStateException("bugs.txt not found");
            }

            return new String(is.readAllBytes(), StandardCharsets.UTF_8)
                    .lines()
                    .map(String::strip)
                    .filter(line -> !line.isEmpty())
                    .toList();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public static List<String> search(String term, int limit) {

        String q = term.toLowerCase(Locale.ROOT);

        return BUGS.stream()
                .filter(bug -> matches(bug.toLowerCase(Locale.ROOT), q))
                .limit(limit)
                .toList();
    }

    private static boolean matches(String bug, String q) {
        return bug.startsWith(q) || bug.contains(" " + q);
    }

    public static boolean exists(String name) {
        return BUGS.contains(name);
    }
}

The service loads the names and searches them.

private static final List<String> BUGS = load();

The static field is initialized once, when the class is first used. All requests then share the same immutable list, so the file is not read again for every keystroke of every user.

    return BUGS.stream()
            .filter(bug -> matches(bug.toLowerCase(Locale.ROOT), q))
            .limit(limit)
            .toList();
}

private static boolean matches(String bug, String q) {
    return bug.startsWith(q) || bug.contains(" " + q);

A name matches when one of its words starts with the term, so both gr and grass find Field grasshopper. Both strings are lowercased with Locale.ROOT, which gives the same result on every server, whatever its default locale. The limit call stops the search when enough names are found.

public static boolean exists(String name) {
    return BUGS.contains(name);
}

The exists method is used later to check the chosen name.

com/zetcode/web/SearchServlet.java
package com.zetcode.web;

import com.google.gson.Gson;
import com.zetcode.service.BugService;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {

    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        String term = request.getParameter("term");
        List<String> names = BugService.search(term, 10);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(gson.toJson(names));
    }
}

The servlet reads the term parameter and returns at most ten matching names as a JSON array. A Gson instance is thread-safe, so one instance serves all requests.

The last request has no term parameter. The getParameter method returns null, the service fails with a NullPointerException, and the client gets a 500 error. We fix this in the next section.

$ curl 'localhost:8080/app/search?term=gr'
["Field grasshopper","Grass grub","Grass looper","Green planthopper","Greenhouse spider"]
$ curl 'localhost:8080/app/search?term=moth'
["Bamboo moth","Banana moth","Cinnabar moth","Clothes moth","Codling moth","Gum emperor moth"]
$ curl 'localhost:8080/app/search?term=g'
["Field grasshopper","Garden slug","Garden soldier fly","German cockroach","German wasp","Giant dragonfly","Giraffe weevil","Grass grub","Grass looper","Green planthopper"]
$ curl -i 'localhost:8080/app/search?term=wasp'
HTTP/1.1 200 OK
Server: Jetty(12.1.15)
Date: Tue, 01 Dec 2026 21:44:45 GMT
Content-Type: application/json;charset=utf-8
Content-Length: 22

["German wasp","Wasp"]
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/app/search
500

Checking the term

The search servlet is public, so it must cope with any input: a missing parameter, white space only, or a long string sent by a script.

com/zetcode/web/SearchServlet.java
package com.zetcode.web;

import com.google.gson.Gson;
import com.zetcode.service.BugService;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {

    private static final int MAX_TERM = 30;
    private static final int MAX_RESULTS = 10;

    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        String term = request.getParameter("term");
        term = term == null ? "" : term.strip();

        if (term.length() > MAX_TERM) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "The term is too long");
            return;
        }

        List<String> names = term.isEmpty()
                ? List.of()
                : BugService.search(term, MAX_RESULTS);

        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "max-age=300");
        response.getWriter().write(gson.toJson(names));
    }
}

The servlet now checks the term before it searches.

String term = request.getParameter("term");
term = term == null ? "" : term.strip();

if (term.length() > MAX_TERM) {
    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
            "The term is too long");
    return;
}

List<String> names = term.isEmpty()
        ? List.of()
        : BugService.search(term, MAX_RESULTS);

A missing term becomes an empty string, and the surrounding white space is removed. An empty term gives an empty array: the user has deleted the text, and the list of suggestions should disappear. No bug name is longer than 30 characters, so a longer term is rejected with 400 Bad Request.

response.setHeader("Cache-Control", "max-age=300");

The same terms come again and again, for example when the user deletes a character. The Cache-Control header lets the browser reuse an answer for five minutes without asking the server.

$ curl localhost:8080/app/search
[]
$ curl 'localhost:8080/app/search?term=%20%20'
[]
$ curl -i 'localhost:8080/app/search?term=%20ci'
HTTP/1.1 200 OK
Server: Jetty(12.1.15)
Date: Tue, 01 Dec 2026 21:44:53 GMT
Content-Type: application/json;charset=utf-8
Cache-Control: max-age=300
Content-Length: 26

["Cicada","Cinnabar moth"]
$ curl -o /dev/null -w '%{http_code}\n' 'localhost:8080/app/search?term=a-very-long-name-of-an-unknown-bug'
400

Filling the list

Now we connect the page to the servlet. The datalist starts empty, and the script fills it whenever the text in the field changes.

src/main/webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bugs</title>
</head>
<body>
    <label for="bug">Bug:</label>
    <input id="bug" list="bugs" autocomplete="off">
    <datalist id="bugs"></datalist>

    <script>
        const input = document.getElementById('bug');
        const list = document.getElementById('bugs');

        input.addEventListener('input', async () => {

            const term = encodeURIComponent(input.value);
            const res = await fetch('search?term=' + term);
            const names = await res.json();

            list.replaceChildren(...names.map(name => new Option(name)));
        });
    </script>
</body>
</html>

The page sends the text of the field to the search servlet and shows the names it returns.

<input id="bug" list="bugs" autocomplete="off">

The autocomplete="off" attribute turns off the browser's own suggestions from previously submitted forms, so they do not mix with ours.

input.addEventListener('input', async () => {

    const term = encodeURIComponent(input.value);
    const res = await fetch('search?term=' + term);
    const names = await res.json();

The input event fires after every change of the value, including pasting and deleting. The encodeURIComponent function escapes characters such as spaces and &, so the term arrives intact. The URL search is relative; it resolves to /app/search.

list.replaceChildren(...names.map(name => new Option(name)));

The Option constructor creates an <option> element with the name as its text and value. The replaceChildren method swaps the old options for the new ones in one step. Since we never build HTML from strings, a name cannot inject markup into the page.

We tested the page in Chromium. Typing gra sent three requests, for g, gr, and gra, and the list ended with Field grasshopper, Grass grub, and Grass looper. One request per keystroke is wasteful. Worse, the responses may arrive in a different order than the requests, and the answer for g can then replace the answer for gra.

Fewer requests

We wait until the user stops typing for a moment, and we cancel a request that is still running when a new one starts.

src/main/webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bugs</title>
</head>
<body>
    <label for="bug">Bug:</label>
    <input id="bug" list="bugs" autocomplete="off">
    <datalist id="bugs"></datalist>

    <script>
        const input = document.getElementById('bug');
        const list = document.getElementById('bugs');

        let timer;
        let controller;

        input.addEventListener('input', () => {
            clearTimeout(timer);
            timer = setTimeout(suggest, 250);
        });

        async function suggest() {

            controller?.abort();
            controller = new AbortController();

            const term = encodeURIComponent(input.value);

            try {
                const res = await fetch('search?term=' + term,
                    { signal: controller.signal });

                if (!res.ok) {
                    return;
                }

                const names = await res.json();
                list.replaceChildren(...names.map(name => new Option(name)));
            } catch (e) {
                if (e.name !== 'AbortError') {
                    throw e;
                }
            }
        }
    </script>
</body>
</html>

The search now runs 250 milliseconds after the last change, and only the latest request may fill the list.

input.addEventListener('input', () => {
    clearTimeout(timer);
    timer = setTimeout(suggest, 250);
});

Each change cancels the planned search and plans a new one. While the user types fast, the timer never fires; the search runs once, when typing pauses. This technique is called debouncing.

controller?.abort();
controller = new AbortController();

const term = encodeURIComponent(input.value);

try {
    const res = await fetch('search?term=' + term,
        { signal: controller.signal });

An AbortController cancels a running request. Before a new search starts, we abort the previous one, so a late answer to an old term can no longer overwrite the list.

    if (!res.ok) {
        return;
    }

    const names = await res.json();
    list.replaceChildren(...names.map(name => new Option(name)));
} catch (e) {
    if (e.name !== 'AbortError') {
        throw e;
    }
}

An aborted fetch rejects with an AbortError, which is expected and ignored. A 400 answer for a too long term leaves the list as it is. In Chromium, typing gra now sent a single request.

Showing the chosen bug

Finally, we put the field into a form and send the chosen name to a second servlet. Because the datalist does not restrict the input, the server must check that the name exists.

com/zetcode/web/BugServlet.java
package com.zetcode.web;

import com.zetcode.service.BugService;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/bug")
public class BugServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        name = name == null ? "" : name.strip();

        if (!BugService.exists(name)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Unknown bug");
            return;
        }

        request.setAttribute("name", name);
        request.getRequestDispatcher("/WEB-INF/bug.jsp")
                .forward(request, response);
    }
}

The servlet accepts only the names from the file and forwards them to a JSP page. Any other value gets 404 Not Found.

src/main/webapp/WEB-INF/bug.jsp
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bug</title>
</head>
<body>
    <p>You have chosen: <c:out value="${name}"/></p>
    <p><a href="./">Choose another bug</a></p>
</body>
</html>

The page prints the name with c:out, which escapes HTML. The name has already been checked, but escaping every value on output is a habit that protects the page when the check changes later. The JSP is under WEB-INF, so clients cannot open it directly.

src/main/webapp/index.html (form)
<form action="bug">
    <label for="bug">Bug:</label>
    <input id="bug" name="name" list="bugs" autocomplete="off" required>
    <datalist id="bugs"></datalist>
    <button>Show</button>
</form>

In index.html, the field and the datalist move into a form; the script stays the same. The input gets the name attribute, which becomes the request parameter, and required blocks an empty submission. In Chromium, choosing Grass grub and clicking the button opened bug?name=Grass+grub.

$ curl 'localhost:8080/app/bug?name=Wolf+spider'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bug</title>
</head>
<body>
    <p>You have chosen: Wolf spider</p>
    <p><a href="./">Choose another bug</a></p>
</body>
</html>
$ curl -o /dev/null -w '%{http_code}\n' 'localhost:8080/app/bug?name=Wolf'
404
$ curl -o /dev/null -w '%{http_code}\n' 'localhost:8080/app/bug?name=%3Cscript%3E'
404

Source

The datalist element, Using the Fetch API, AbortController, and the Jakarta Servlet 6.1 specification.

In this article we have built an autocomplete field with a search servlet, an HTML datalist, and the Fetch API. The servlet checks the term and limits the results, and the page waits for a pause in typing and drops stale requests. The datalist is simple, but its look and matching are up to the browser; for a styled list, the same servlet can serve a custom drop-down. Tables that load their data from servlets are covered in Java Servlet Tabulator and Java Servlet Grid.js.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Java Servlet tutorials.