Java Servlet chart tutorial

In this tutorial, we create a pie chart with JFreeChart and serve from a Java servlet.

Servlet is a Java class which responds to a particular type of network request - most commonly an HTTP request. Servlets are used to implement web applications in Java. They run in a servlet container such as Tomcat or Jetty. In modern days, Java web programmers use frameworks that are built on top of servlets to develop applications.

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

JFreeChart is a popular Java chart library. It allows to create a variety of both interactive and non-interactive charts.

Java Servlet chart example

The following example creates a pie chart with JFreeChart library and serves it in a Java Servlet.

context.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>ServletChartEx</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ServletChartEx</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>4.0.0</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.19</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>

The javax.servlet-api dependency is a library for building Java servlets. The jfreechart is a dependency for JFreeChart library. The maven-war-plugin collects all artifact dependencies, classes and resources of the web application and packages them into a web application archive (WAR).

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

In the context.xml file, we set the context path (the application name).

$ tree
.
├── nb-configuration.xml
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zetcode
        │           └── chartinservletex
        │               └── DoChart.java
        ├── resources
        └── webapp
            ├── index.html
            ├── META-INF
            │   └── context.xml
            └── WEB-INF

With the tree command we show the project directory structure.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Chart</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="UTF-8">
    </head>
    <body>
        <a href="showChart">Show chart</a>
    </body>
</html>

In the index.html file, we have a link that calls a servlet, which servers the chart.

DoChart.java
package com.zetcode.chartinservletex;

import java.io.IOException;
import java.io.OutputStream;
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 org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

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

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

        response.setContentType("image/png");

        OutputStream os = response.getOutputStream();

        JFreeChart chart = getChart();
        int width = 500;
        int height = 350;
        
        ChartUtilities.writeChartAsPNG(os, chart, width, height);
    }

    public JFreeChart getChart() {
        
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Croatia", 22);
        dataset.setValue("Bohemia", 34);
        dataset.setValue("Bulgaria", 18);
        dataset.setValue("Spain", 5);
        dataset.setValue("Others", 21);

        JFreeChart chart = ChartFactory.createPieChart("Popular destinations", 
                dataset, true, false, false);

        chart.setBorderVisible(false);

        return chart;
    }
}

The DoChart servlet returns a pie chart to the client.

@WebServlet(name = "DoChart", urlPatterns = {"/showChart"})

The @WebServlet annotation maps the request with showChart URL pattern to the DoChart servlet.

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

The request is a GET request, so we serve it in the doGet() method.

response.setContentType("image/png");

The chart is served as an image in the PNG format; therefore, we set the content type of the response to image/png.

OutputStream os = response.getOutputStream();

From the response object, we get the OutputStream. We serve the chart to the client by writing to the servlet's OutputStream.

ChartUtilities.writeChartAsPNG(os, chart, width, height);

The ChartUtilities.writeChartAsPNG() writes converts the chart into a PNG file and writes it into the output stream.

public JFreeChart getChart() {
    
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Croatia", 22);
    dataset.setValue("Bohemia", 34);
    dataset.setValue("Bulgaria", 18);
    dataset.setValue("Spain", 5);
    dataset.setValue("Others", 21);

    JFreeChart chart = ChartFactory.createPieChart("Popular destinations", 
            dataset, true, false, false);

    chart.setBorderVisible(false);

    return chart;
}

In the getChart() method, we generate the chart. The DefaultPieDataset contains the data for the pie chart.

JFreeChart chart = ChartFactory.createPieChart("Popular destinations", 
        dataset, true, false, false);

The pie chart is created with ChartFactory.createPieChart().

In this tutorial, we have used created a pie chart with JFreeChart library in a Java servlet and served it to the client.

You might also be interested in the following related tutorials: JFreeChart tutorial, Java tutorial, Java Servlet image tutorial, Serving image file in Spring Boot, or Java Servlet JSON tutorial.