ZetCode

Java Servlet Tabulator

last modified November 30, 2026

In this article we show how to display and edit database data in a Tabulator grid. A Jakarta servlet reads the rows from an H2 database and exchanges them with the grid as JSON. The grid loads, adds, edits, and deletes cars with the HTTP GET, POST, PUT, and DELETE methods.

Tabulator is an open source JavaScript library for interactive tables, released under the MIT license. It has no dependencies; in particular, it does not need jQuery. It supports sorting, pagination, in-place cell editing, and loading data with Ajax.

H2 is a relational database written in Java. We run it in memory inside the web application, so the example needs no database server.

The servlet produces JSON with the Gson library, which is introduced in the Java servlet JSON article. For a read-only table with server-side paging, searching, and sorting, see Java Servlet Grid.js.

Project setup

We start from the Maven project described in the Java Servlet introduction: Java 25, Jakarta Servlet 6.1, and the Jetty 12.1 Maven plugin with the /app context path. We add two dependencies to the POM file.

pom.xml (dependencies)
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.5.252</version>
</dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.15.0</version>
</dependency>

The h2 artifact contains both the database engine and its JDBC driver. The gson library converts Java objects to JSON and back.

This is the project structure of the finished application.

.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zetcode
        │           ├── Car.java
        │           ├── CarRepository.java
        │           ├── CarsServlet.java
        │           └── Database.java
        ├── resources
        │   └── cars.sql
        └── webapp
            ├── app.js
            ├── index.html
            └── static.html

Tabulator with static data

Before we connect the grid to a servlet, we create it from a JavaScript array. This shows the minimal Tabulator setup.

src/main/webapp/static.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cars</title>
    <link href="https://unpkg.com/tabulator-tables@6.7.1/dist/css/tabulator.min.css"
          rel="stylesheet">
    <script src="https://unpkg.com/tabulator-tables@6.7.1/dist/js/tabulator.min.js"></script>
</head>
<body>

<div id="cars"></div>

<script>
    new Tabulator("#cars", {
        data: [
            {id: 1, name: "Audi", price: 52642},
            {id: 2, name: "Mercedes", price: 57127},
            {id: 3, name: "Skoda", price: 9000}
        ],
        layout: "fitColumns",
        columns: [
            {title: "Id", field: "id", width: 70},
            {title: "Name", field: "name"},
            {title: "Price", field: "price", hozAlign: "right"}
        ]
    });
</script>

</body>
</html>

The page loads the Tabulator stylesheet and script from the unpkg CDN and creates a grid in the cars element.

new Tabulator("#cars", {

The first argument is a CSS selector of the element that holds the grid; the second is the configuration object.

data: [
    {id: 1, name: "Audi", price: 52642},

Each row is an object. Tabulator finds the cell values by the property names.

{title: "Price", field: "price", hozAlign: "right"}

A column definition maps a field of the row objects to a column with a title. The fitColumns layout stretches the columns to the width of the table.

We run the application with mvn jetty:run and open localhost:8080/app/static.html.

Tabulator with static data
Figure: Tabulator with static data

The database

The cars are stored in an in-memory H2 database. An SQL script in the application resources creates and fills the table.

src/main/resources/cars.sql
DROP TABLE IF EXISTS cars;

CREATE TABLE cars(id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL, price INT NOT NULL);

INSERT INTO cars(name, price) VALUES('Audi', 52642), ('Mercedes', 57127),
    ('Skoda', 9000), ('Volvo', 29000), ('Bentley', 350000),
    ('Citroen', 21000), ('Hummer', 41400), ('Volkswagen', 21600),
    ('Toyota', 26700), ('Peugeot', 18900), ('Mazda', 24300),
    ('Porsche', 98000);

The id column is generated by the database. The script drops the table first, so it can be run repeatedly.

com/zetcode/Database.java
package com.zetcode;

import org.h2.jdbcx.JdbcDataSource;

import javax.sql.DataSource;
import java.sql.SQLException;

public final class Database {

    private static final JdbcDataSource DS = new JdbcDataSource();

    static {
        DS.setURL("jdbc:h2:mem:cars;DB_CLOSE_DELAY=-1");
        DS.setUser("sa");
    }

    private Database() {
    }

    public static DataSource dataSource() {
        return DS;
    }

    public static void init() throws SQLException {

        try (var con = DS.getConnection();
             var stm = con.createStatement()) {

            stm.execute("RUNSCRIPT FROM 'classpath:/cars.sql'");
        }
    }
}

The Database class holds a single data source and runs the SQL script.

DS.setURL("jdbc:h2:mem:cars;DB_CLOSE_DELAY=-1");

The mem: URL creates an in-memory database. By default, H2 removes it when the last connection closes; DB_CLOSE_DELAY=-1 keeps it alive while the server runs.

stm.execute("RUNSCRIPT FROM 'classpath:/cars.sql'");

The RUNSCRIPT command executes the script from the class path. Maven copies src/main/resources to WEB-INF/classes, so the script is found inside the WAR as well.

Sending cars as JSON

The first version of the servlet only reads the cars. A record represents one row of the table.

com/zetcode/Car.java
package com.zetcode;

public record Car(Integer id, String name, int price) {
}

The id is an Integer, because a new car sent by the client has no id yet. Gson serializes records by their component names.

com/zetcode/CarRepository.java
package com.zetcode;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CarRepository {

    private final DataSource ds = Database.dataSource();

    public List<Car> findAll() throws SQLException {

        var sql = "SELECT id, name, price FROM cars ORDER BY id";

        try (var con = ds.getConnection();
             var pst = con.prepareStatement(sql);
             var rs = pst.executeQuery()) {

            var cars = new ArrayList<Car>();

            while (rs.next()) {
                cars.add(new Car(rs.getInt("id"), rs.getString("name"),
                        rs.getInt("price")));
            }

            return cars;
        }
    }
}

The findAll method reads all cars ordered by their id. The try-with-resources statement closes the result set, the statement, and the connection.

com/zetcode/CarsServlet.java
package com.zetcode;

import com.google.gson.Gson;
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;
import java.sql.SQLException;

@WebServlet(urlPatterns = {"/cars/*"})
public class CarsServlet extends HttpServlet {

    private final CarRepository repository = new CarRepository();
    private final Gson gson = new Gson();

    @Override
    public void init() throws ServletException {

        try {
            Database.init();
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

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

        try {
            sendJson(response, repository.findAll());
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    private void sendJson(HttpServletResponse response, Object data)
            throws IOException {

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

The servlet creates the database in init and returns the cars in doGet.

@WebServlet(urlPatterns = {"/cars/*"})

The /cars/* pattern matches both /cars and addresses such as /cars/3, which we need later for updates and deletions.

response.setContentType("application/json;charset=UTF-8");
gson.toJson(data, response.getWriter());

The content type is set before the writer is obtained. Gson writes the list directly to the response writer.

$ curl localhost:8080/app/cars
[{"id":1,"name":"Audi","price":52642},{"id":2,"name":"Mercedes","price":57127},{"id":3,"name":"Skoda","price":9000},{"id":4,"name":"Volvo","price":29000},{"id":5,"name":"Bentley","price":350000},{"id":6,"name":"Citroen","price":21000},{"id":7,"name":"Hummer","price":41400},{"id":8,"name":"Volkswagen","price":21600},{"id":9,"name":"Toyota","price":26700},{"id":10,"name":"Peugeot","price":18900},{"id":11,"name":"Mazda","price":24300},{"id":12,"name":"Porsche","price":98000}]

Loading the grid from the servlet

Now the grid gets its rows from the servlet. We move the script to a separate file.

src/main/webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cars</title>
    <link href="https://unpkg.com/tabulator-tables@6.7.1/dist/css/tabulator.min.css"
          rel="stylesheet">
    <script src="https://unpkg.com/tabulator-tables@6.7.1/dist/js/tabulator.min.js"></script>
</head>
<body>

<div id="cars"></div>

<script src="app.js"></script>

</body>
</html>

The page contains the grid element and loads app.js.

src/main/webapp/app.js
const url = "cars";

const table = new Tabulator("#cars", {
    ajaxURL: url,
    layout: "fitColumns",
    pagination: true,
    paginationSize: 5,
    columns: [
        {title: "Id", field: "id", width: 70},
        {title: "Name", field: "name"},
        {title: "Price", field: "price", hozAlign: "right"}
    ]
});

Instead of data, we set ajaxURL. Tabulator sends a GET request and expects an array of row objects in the response. The relative URL cars resolves to /app/cars.

pagination: true,
paginationSize: 5,

The grid shows five rows per page. The data is loaded once and paged in the browser.

Tabulator loaded from a servlet
Figure: Tabulator loaded from a servlet

Adding cars

A new car is created with a POST request whose body is a JSON object. We add an insert method to the repository.

com/zetcode/CarRepository.java (insert)
public Car insert(Car car) throws SQLException {

    var sql = "INSERT INTO cars(name, price) VALUES(?, ?)";

    try (var con = ds.getConnection();
         var pst = con.prepareStatement(sql,
                 Statement.RETURN_GENERATED_KEYS)) {

        pst.setString(1, car.name());
        pst.setInt(2, car.price());
        pst.executeUpdate();

        try (var keys = pst.getGeneratedKeys()) {
            keys.next();
            return new Car(keys.getInt(1), car.name(), car.price());
        }
    }
}

The RETURN_GENERATED_KEYS flag makes the generated id available through getGeneratedKeys. The method returns the stored car with its new id. The class now also imports java.sql.Statement.

com/zetcode/CarsServlet.java (doPost)
@Override
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    Car car = readCar(request);

    if (car == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    try {
        Car saved = repository.insert(car);

        response.setStatus(HttpServletResponse.SC_CREATED);
        response.setHeader("Location",
                request.getRequestURI() + "/" + saved.id());
        sendJson(response, saved);
    } catch (SQLException e) {
        throw new ServletException(e);
    }
}

private Car readCar(HttpServletRequest request) throws IOException {

    request.setCharacterEncoding("UTF-8");

    try {
        Car car = gson.fromJson(request.getReader(), Car.class);

        if (car == null || car.name() == null || car.name().isBlank()
                || car.name().length() > 30 || car.price() < 0) {
            return null;
        }

        return car;
    } catch (JsonParseException e) {
        return null;
    }
}

The doPost method reads the car, stores it, and answers with 201 Created. The class now also imports com.google.gson.JsonParseException.

response.setHeader("Location",
        request.getRequestURI() + "/" + saved.id());

The Location header contains the address of the new resource. The body contains the car with its id, which the grid needs for later updates.

request.setCharacterEncoding("UTF-8");

Browsers do not send a charset with application/json, so we set the request encoding before calling getReader.

if (car == null || car.name() == null || car.name().isBlank()
        || car.name().length() > 30 || car.price() < 0) {
    return null;
}

Invalid input and malformed JSON both lead to 400 Bad Request. The length check matches the VARCHAR(30) column.

On the client, we add a button above the grid in index.html.

<button id="add">Add car</button>

In app.js, a small helper sends JSON requests, and the button handler uses it to create a car.

src/main/webapp/app.js (additions)
async function send(method, path, body) {

    const res = await fetch(path, {
        method: method,
        headers: {"Content-Type": "application/json"},
        body: body ? JSON.stringify(body) : undefined
    });

    if (!res.ok) {
        throw new Error(`${method} ${path} failed: ${res.status}`);
    }

    return res.status === 204 ? null : res.json();
}

document.querySelector("#add").addEventListener("click", async () => {

    const car = await send("POST", url, {name: "New car", price: 0});
    table.addRow(car, true);
});

The send function is placed after the url constant; the handler goes after the table. send throws an error for a non-2xx status. For 204 No Content there is no body to parse.

table.addRow(car, true);

The second argument adds the row at the top of the table, so the new car is visible immediately.

$ curl -i -X POST -H 'Content-Type: application/json' -d '{"name":"Lexus","price":45000}' localhost:8080/app/cars
HTTP/1.1 201 Created
Server: Jetty(12.1.15)
Date: Mon, 30 Nov 2026 21:51:10 GMT
Location: /app/cars/13
Content-Type: application/json;charset=utf-8
Content-Length: 38

{"id":13,"name":"Lexus","price":45000}

Editing cells

An edited row is sent with a PUT request to /cars/{id}. The repository gets an update method.

com/zetcode/CarRepository.java (update)
public boolean update(int id, Car car) throws SQLException {

    var sql = "UPDATE cars SET name = ?, price = ? WHERE id = ?";

    try (var con = ds.getConnection();
         var pst = con.prepareStatement(sql)) {

        pst.setString(1, car.name());
        pst.setInt(2, car.price());
        pst.setInt(3, id);

        return pst.executeUpdate() == 1;
    }
}

The method returns false when no row has the given id.

com/zetcode/CarsServlet.java (doPut)
@Override
protected void doPut(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    Integer id = readId(request);
    Car car = readCar(request);

    if (id == null || car == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    try {
        if (repository.update(id, car)) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (SQLException e) {
        throw new ServletException(e);
    }
}

private Integer readId(HttpServletRequest request) {

    String path = request.getPathInfo();

    if (path == null || !path.matches("/\\d{1,9}")) {
        return null;
    }

    return Integer.valueOf(path.substring(1));
}

The id comes from the path. For /app/cars/3, getPathInfo returns /3. The regular expression accepts only digits, so any other path yields 400. An unknown id yields 404 Not Found; a successful update returns 204 No Content.

In app.js, the Name and Price columns get editors.

{title: "Name", field: "name", editor: "input"},
{title: "Price", field: "price", editor: "number", hozAlign: "right"},

Clicking a cell opens an input; the number editor returns a number, not a string. When an edit is finished, Tabulator fires the cellEdited event.

src/main/webapp/app.js (additions)
table.on("cellEdited", async cell => {

    const car = cell.getRow().getData();

    try {
        await send("PUT", `${url}/${car.id}`, car);
    } catch (err) {
        cell.restoreOldValue();
        alert(err.message);
    }
});

The handler sends the whole row. If the server rejects it, for example because the name is empty, restoreOldValue puts the previous value back into the cell.

$ curl -i -X PUT -H 'Content-Type: application/json' -d '{"name":"Skoda","price":9500}' localhost:8080/app/cars/3
HTTP/1.1 204 No Content
Server: Jetty(12.1.15)
Date: Mon, 30 Nov 2026 21:51:10 GMT

$ curl -i -X PUT -H 'Content-Type: application/json' -d '{"name":"","price":9500}' localhost:8080/app/cars/3
HTTP/1.1 400 Bad Request

Deleting cars

The last operation removes a car with a DELETE request. The repository method mirrors update.

com/zetcode/CarRepository.java (delete)
public boolean delete(int id) throws SQLException {

    var sql = "DELETE FROM cars WHERE id = ?";

    try (var con = ds.getConnection();
         var pst = con.prepareStatement(sql)) {

        pst.setInt(1, id);

        return pst.executeUpdate() == 1;
    }
}

The method reports whether a row was deleted.

com/zetcode/CarsServlet.java (doDelete)
@Override
protected void doDelete(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    Integer id = readId(request);

    if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    try {
        if (repository.delete(id)) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (SQLException e) {
        throw new ServletException(e);
    }
}

The servlet reuses readId; a DELETE request has no body.

In app.js, we add a fourth column with a delete button and a function that removes the car.

src/main/webapp/app.js (additions)
{formatter: "buttonCross", width: 50, hozAlign: "center",
    headerSort: false, cellClick: (e, cell) => removeCar(cell.getRow())}

async function removeCar(row) {

    await send("DELETE", `${url}/${row.getData().id}`);
    row.delete();
}

The buttonCross formatter draws a cross in each cell of the column. The row is removed from the grid only after the server confirms the deletion.

$ curl -i -X DELETE localhost:8080/app/cars/13
HTTP/1.1 204 No Content
Server: Jetty(12.1.15)
Date: Mon, 30 Nov 2026 21:51:11 GMT

$ curl -i -X DELETE localhost:8080/app/cars/13
HTTP/1.1 404 Not Found

Running the application

We start Jetty and open localhost:8080/app/. Clicking a Name or Price cell opens an editor; pressing Enter saves the change. The data lives in memory, so it is reset when the server restarts.

$ mvn jetty:run
Editing a cell in Tabulator
Figure: Editing a cell in Tabulator

Source

Tabulator documentation, H2 database, and the Jakarta Servlet 6.1 specification.

In this article we displayed and edited database data in a Tabulator grid. A Jakarta servlet mapped the GET, POST, PUT, and DELETE methods to JDBC operations and exchanged the data as JSON. For a read-only table with server-side paging, see Java Servlet Grid.js; server-rendered paging is covered in Java Servlet pagination.

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.