ZetCode

Java Servlet Grid.js

last modified November 30, 2026

In this article we show how to display database data in a Grid.js table. A Jakarta servlet returns the cars from an H2 database as JSON. The paging, searching, and sorting are done on the server, so the browser receives only the rows it shows.

Grid.js is an open source JavaScript table library, released under the MIT license. It has no dependencies and works with plain JavaScript as well as with front-end frameworks. It supports pagination, search, and sorting, either in the browser or through a server.

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 table in this article is read-only. Editing rows in a grid is covered in Java Servlet Tabulator, and paging rendered with JSP on the server in Java Servlet pagination. JSON output with Gson is introduced in Java servlet JSON.

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.

This is the project structure of the finished application.

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

Grid.js with static data

Before we connect the table to a servlet, we create it from a JavaScript array. This shows the minimal Grid.js setup.

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

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

<script>
    new gridjs.Grid({
        columns: ["Id", "Name", "Price"],
        data: [
            [1, "Audi", 52642],
            [2, "Mercedes", 57127],
            [3, "Skoda", 9000]
        ]
    }).render(document.getElementById("cars"));
</script>

</body>
</html>

The page loads the Grid.js script and its mermaid theme from the unpkg CDN. The library is available as the global gridjs object.

columns: ["Id", "Name", "Price"],
data: [
    [1, "Audi", 52642],

The column names are plain strings, and each row is an array of cell values in column order.

}).render(document.getElementById("cars"));

The render method draws the table into the given element.

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

Grid.js with static data
Figure: Grid.js with static data

The database

The cars are stored in an in-memory H2 database. The setup is the same as in the Tabulator article. 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);

Twelve rows are enough to fill three pages of five rows.

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 mem: URL creates an in-memory database, and DB_CLOSE_DELAY=-1 keeps it alive while the server runs. The RUNSCRIPT command executes cars.sql from the class path.

Sending cars as JSON

The first version of the servlet returns all 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) {
}

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 {
            response.setContentType("application/json;charset=UTF-8");
            gson.toJson(repository.findAll(), response.getWriter());
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
}

The servlet creates the database in init and writes the list of cars as JSON in doGet. The content type is set before the writer is obtained.

$ 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 table from the servlet

Now the table 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/gridjs@6.2.0/dist/theme/mermaid.min.css"
          rel="stylesheet">
    <script src="https://unpkg.com/gridjs@6.2.0/dist/gridjs.umd.js"></script>
</head>
<body>

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

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

</body>
</html>

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

src/main/webapp/app.js
new gridjs.Grid({
    columns: ["Id", "Name", "Price"],
    server: {
        url: "cars",
        then: cars => cars.map(car => [car.id, car.name, car.price])
    }
}).render(document.getElementById("cars"));

The server option replaces data. Grid.js fetches the url, which resolves to /app/cars, and passes the parsed JSON to then. The function turns each car object into an array of cells.

Grid.js loaded from a servlet
Figure: Grid.js loaded from a servlet

Server-side paging

With many rows, sending the whole table is wasteful. The servlet now accepts limit and offset parameters and returns one page together with the total number of rows.

com/zetcode/CarPage.java
package com.zetcode;

import java.util.List;

public record CarPage(int total, List<Car> cars) {
}

Grid.js needs the total to compute the number of pages.

com/zetcode/CarRepository.java (count, findPage)
public int count() throws SQLException {

    var sql = "SELECT COUNT(*) FROM cars";

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

        rs.next();
        return rs.getInt(1);
    }
}

public List<Car> findPage(int limit, int offset) throws SQLException {

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

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

        pst.setInt(1, limit);
        pst.setInt(2, offset);

        try (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 two methods replace findAll. The LIMIT and OFFSET clauses select one page. The ORDER BY clause is required; without it, the database may return the rows of a page in any order.

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

    int limit = intParam(request, "limit", 5, 1, 50);
    int offset = intParam(request, "offset", 0, 0, Integer.MAX_VALUE);

    try {
        var page = new CarPage(repository.count(),
                repository.findPage(limit, offset));

        response.setContentType("application/json;charset=UTF-8");
        gson.toJson(page, response.getWriter());
    } catch (SQLException e) {
        throw new ServletException(e);
    }
}

private int intParam(HttpServletRequest request, String name,
        int defaultValue, int min, int max) {

    try {
        int value = Integer.parseInt(request.getParameter(name));
        return Math.clamp(value, min, max);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

The intParam method reads a number from the request. A missing or malformed value gives the default; Math.clamp keeps the value within limits, so a client cannot request a million rows at once.

On the client, the then function now reads the cars property, and we add the total and pagination options.

src/main/webapp/app.js
function join(prev, param) {
    return prev + (prev.includes("?") ? "&" : "?") + param;
}

new gridjs.Grid({
    columns: ["Id", "Name", "Price"],
    server: {
        url: "cars",
        then: data => data.cars.map(car => [car.id, car.name, car.price]),
        total: data => data.total
    },
    pagination: {
        limit: 5,
        server: {
            url: (prev, page, limit) =>
                join(prev, `limit=${limit}&offset=${page * limit}`)
        }
    }
}).render(document.getElementById("cars"));

Grid.js builds the request URL from server.url and passes it as prev to the pagination.server.url function. The page argument is zero-based. The join helper adds a parameter with ? or &; we need it again for searching and sorting.

$ curl 'localhost:8080/app/cars?limit=5&offset=5'
{"total":12,"cars":[{"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}]}
$ curl 'localhost:8080/app/cars?limit=abc&offset=-3'
{"total":12,"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}]}

Searching

Next we filter the cars by name. The search term arrives in the q parameter, and both repository methods take it into account.

com/zetcode/CarRepository.java (count, findPage, pattern)
public int count(String q) throws SQLException {

    var sql = "SELECT COUNT(*) FROM cars WHERE LOWER(name) LIKE ?";

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

        pst.setString(1, pattern(q));

        try (var rs = pst.executeQuery()) {
            rs.next();
            return rs.getInt(1);
        }
    }
}

public List<Car> findPage(String q, int limit, int offset)
        throws SQLException {

    var sql = """
            SELECT id, name, price FROM cars WHERE LOWER(name) LIKE ?
            ORDER BY id LIMIT ? OFFSET ?""";

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

        pst.setString(1, pattern(q));
        pst.setInt(2, limit);
        pst.setInt(3, offset);

        try (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;
        }
    }
}

private String pattern(String q) {
    return "%" + (q == null ? "" : q.strip().toLowerCase()) + "%";
}

The count method must use the same condition as findPage; otherwise the number of pages would be wrong. The search term is passed as a parameter, never concatenated into the SQL. LOWER on both sides makes the search case-insensitive, and a missing term matches every row.

String q = request.getParameter("q");

var page = new CarPage(repository.count(q),
        repository.findPage(q, limit, offset));

The servlet reads the parameter and passes it to both methods.

search: {
    server: {
        url: (prev, keyword) =>
            join(prev, `q=${encodeURIComponent(keyword)}`)
    }
},

In app.js, we add the search option before pagination. Grid.js shows a search box and calls the function with the typed keyword. The keyword must be URL-encoded.

$ curl 'localhost:8080/app/cars?q=au'
{"total":1,"cars":[{"id":1,"name":"Audi","price":52642}]}

Sorting

Finally, the user can sort by clicking a column header. The servlet receives the column in sort and the direction in dir.

com/zetcode/CarRepository.java (findPage)
private static final Set<String> COLUMNS = Set.of("id", "name", "price");

public List<Car> findPage(String q, String sort, boolean asc,
        int limit, int offset) throws SQLException {

    String column = sort != null && COLUMNS.contains(sort) ? sort : "id";
    String dir = asc ? "ASC" : "DESC";

    var sql = """
            SELECT id, name, price FROM cars WHERE LOWER(name) LIKE ?
            ORDER BY %s %s, id LIMIT ? OFFSET ?""".formatted(column, dir);

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

        pst.setString(1, pattern(q));
        pst.setInt(2, limit);
        pst.setInt(3, offset);

        try (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;
        }
    }
}

A column name cannot be passed as a JDBC parameter; it must be part of the SQL text. To prevent SQL injection, we accept only names from the COLUMNS set and fall back to id. The null check is needed, because Set.of collections throw NullPointerException for contains(null). The second sort key, id, keeps the order stable for equal values. The class now also imports java.util.Set.

String sort = request.getParameter("sort");
boolean asc = !"desc".equals(request.getParameter("dir"));

The servlet reads both parameters; any value other than desc means ascending order. They are passed to findPage.

src/main/webapp/app.js (sort option)
sort: {
    multiColumn: false,
    server: {
        url: (prev, columns) => {

            if (!columns.length) {
                return prev;
            }

            const col = columns[0];
            const field = ["id", "name", "price"][col.index];
            const dir = col.direction === 1 ? "asc" : "desc";

            return join(prev, `sort=${field}&dir=${dir}`);
        }
    }
},

The sort option goes before pagination. Grid.js passes the sorted columns with their index and direction; 1 means ascending and -1 descending. We map the index to a field name. With multiColumn: false, only one column is sorted at a time.

$ curl 'localhost:8080/app/cars?sort=price&dir=desc&limit=3'
{"total":12,"cars":[{"id":5,"name":"Bentley","price":350000},{"id":12,"name":"Porsche","price":98000},{"id":2,"name":"Mercedes","price":57127}]}
$ curl 'localhost:8080/app/cars?sort=price;DROP%20TABLE%20cars&limit=3'
{"total":12,"cars":[{"id":1,"name":"Audi","price":52642},{"id":2,"name":"Mercedes","price":57127},{"id":3,"name":"Skoda","price":9000}]}
$ curl 'localhost:8080/app/cars?q=o&sort=name&limit=3&offset=3'
{"total":7,"cars":[{"id":3,"name":"Skoda","price":9000},{"id":9,"name":"Toyota","price":26700},{"id":8,"name":"Volkswagen","price":21600}]}

Running the application

We start Jetty and open localhost:8080/app/. Typing into the search box, clicking a header, or changing the page sends a new request with all three settings combined.

$ mvn jetty:run
Grid.js sorted by price
Figure: Grid.js sorted by price in descending order

Source

Grid.js documentation, H2 database, and the Jakarta Servlet 6.1 specification.

In this article we displayed database data in a Grid.js table. A Jakarta servlet implemented paging, searching, and sorting with JDBC and returned one page of JSON at a time. For an editable grid, see Java Servlet Tabulator; 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.