Java Servlet JQuery list tutorial

In Java Servlet JQuery list tutorial, we show how to fetch data from a Java servlet with JQuery and display it in a HTML list. We use Gson library to work with JSON data format. The web application is deployed on Tomcat server.

Apache Tomcat is an open source Java Servlet container developed by the Apache Software Foundation (ASF). It is the most popular Java web server.

Java Servlet

Servlet is a Java class which responds to a particular type of network request - most commonly an HTTP request. Java servlets are used to create web applications. They run in servlet containers such as Tomcat or Jetty. Modern-day Java web development uses frameworks that are built on top of servlets.

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. It is less verbose and more readable than XML. The official Internet media type for JSON is application/json. The JSON filename extension is .json. JSON is directly consumable by JavaScript.

Gson

Gson is an open source Java library to serialize and deserialize Java objects to (and from) JSON. Gson was created by Google.

Java servlet JQuery list example

The following web application uses a Java servlet to send data (list of cities) to the client in JSON format. JQuery is used to execute the request and dynamically build the HTML list.

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── bean
    │   │           │   └── City.java
    │   │           ├── service
    │   │           │   └── CityService.java
    │   │           └── web
    │   │               └── GetCities.java
    │   ├── resources
    │   └── webapp
    │       ├── index.html
    │       ├── META-INF
    │       │   └── context.xml
    │       └── WEB-INF
    └── test
        └── java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>com.zetcode</groupId>
    <artifactId>JavaServleJqueryList</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>JavaServleJqueryList</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <dependencies>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
 
        </plugins>
    </build>
</project>

This is the Maven POM file. We have two artifacts: javax.servlet-api for servlets and gson for JSON processing in Java. The maven-war-plugin is responsible for collecting all artifact dependencies, classes and resources of the web application and packaging them into a web application archive (WAR).

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/JavaServleJqueryList"/>

In the Tomcat context.xml file, we define the context path. It is the name of the web application.

City.java
package com.zetcode.bean;

import com.google.gson.annotations.Expose;

public class City {

    private Long id;
    
    @Expose
    private String name;
    @Expose
    private int population;

    public City() {
    }

    public City(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public String toString() {
        return "City{" + "id=" + id + ", name=" + name + 
                ", population=" + population + '}';
    }
}

This is the City bean. It has three attributes: id, name, and population. The Gson's @Expose annotation indicates which members should be exposed for JSON serialization or deserialization. In our case, we omit the id since it is not relevant for our client. This way we save some bandwidth.

GetCities.java
package com.zetcode.web;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zetcode.bean.City;
import com.zetcode.service.CityService;
import java.io.IOException;
import java.io.PrintWriter;
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;

@WebServlet(name = "GetCities", urlPatterns = {"/GetCities"})
public class GetCities extends HttpServlet {

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

        response.setContentType("application/json;charset=UTF-8");

        try (PrintWriter out = response.getWriter()) {

            List<City> cities = CityService.getCities();
            
            Gson gson = new GsonBuilder()
                    .excludeFieldsWithoutExposeAnnotation()
                    .create();

            out.print(gson.toJson(cities));
        }
    }
}

This is the GetCities servlet. It retrieves data from a service class and returns them to the client in JSON format.

response.setContentType("application/json;charset=UTF-8");

We set the content type of the response object to application/json.

try (PrintWriter out = response.getWriter()) {

We get the PrintWriter which is used to send character text to the client.

List<City> cities = CityService.getCities();

From the CityService, we get the list of cities.

Gson gson = new GsonBuilder()
        .excludeFieldsWithoutExposeAnnotation()
        .create();

We create and configure the Gson class, which is the main class for using Gson. The excludeFieldsWithoutExposeAnnotation() enables the @Expose annotations.

out.print(gson.toJson(cities));

With the toJson() method, we transform a Java list into JSON array. The array is written to the writer. The array was not given a name.

CityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.ArrayList;
import java.util.List;

public class CityService {

    public static List<City> getCities() {

        List<City> cities = new ArrayList<>();
        
        cities.add(new City(1L, "Bratislava", 432000));
        cities.add(new City(2L, "Budapest", 1759000));
        cities.add(new City(3L, "Prague", 1280000));
        cities.add(new City(4L, "Warsaw", 1748000));
        cities.add(new City(5L, "Los Angeles", 3971000));
        cities.add(new City(6L, "New York", 8550000));
        cities.add(new City(7L, "Edinburgh", 464000));
        cities.add(new City(8L, "Berlin", 3671000));
        
        return cities;
    }
}

The CityService's getCities() method returns a list of city objects.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta charset="UTF-8">
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
    </head>
    <body>

        <button id="mybtn">Get cities</button>

        <div>
            <ul id="output">

            </ul>
        </div>

        <script>
            $('#mybtn').click(function () {

                $.getJSON('GetCities', function (data) {
                    
                    $("ul#output > li").remove();
                    
                    $.each(data, function (key, value) {
                        $("#output").append('<li>' + value['name'] + " " + value['population'] + '</li>');
                    });
                });
            });
        </script>
    </body>
</html>

This is the home page.

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 

We include the JQuery library.

<button id="mybtn">Get cities</button>

This button executes the request.

<div>
    <ul id="output">

    </ul>
</div>

The returned data will be written inside these elements.

$('#mybtn').click(function () {

    $.getJSON('GetCities', function (data) {
        
        $("ul#output > li").remove();
        
        $.each(data, function (key, value) {
            $("#output").append('<li>' + value['name'] + " " + value['population'] + '</li>');
        });
    });
});

We add a click event handler for the button. The $.getJSON() method loads JSON-encoded data from the GetCities servlet using a GET HTTP request. With the remove() method we delete previous elements, if present. With $.each() we go over the JSON data and append it to the output inside <li> tags.

Java Servlet JQuery list example
Figure: Java Servlet JQuery list example

In the figure we can see the data in the HTML list: the cities and their population.

In this tutorial, we have used JQuery to get JSON data from a Java servlet and build an HTML list.

You might also be interested in the following related tutorials: Gson tutorial, Java servlet JSON tutorial, Serving plain text from Java servlet, Java servlet check box tutorial, Java servlet image tutorial, Java Servlet HTTP headers, or Java tutorial