Google Chart using JSP, Servlet

Here I am going to show you how to display data on Google Pie Chart using JSP and Servlet. You know that Google chart basically displays different statistical data on different chart types such as column chart, bar chart, line chart, pie chart etc. You can have a look at the URL https://developers.google.com/chart/ for more information.

You can integrate Google chart with any server side technology but here I will show you how to integrate Google chart with JSP, Servlet. It displays the data for area-wise top seven countries in the world. You can also use other charts for other purposes. In this example I have used sample data and the actual data should come from database or other sources. You can change the source of data as per your requirements.

Project Setup

You can create either gradle or maven project in your favorite tool or IDE. The following gradle build file (build.gradle) shows the required configurations:

plugins {
	id 'war'
    id 'java-library'
}

repositories {
    jcenter()
}

dependencies {
    providedCompile 'javax.servlet:javax.servlet-api:4.0.1'
    implementation 'javax.servlet.jsp:jsp-api:2.2'
    implementation 'org.apache.taglibs:taglibs-standard-impl:1.2.5'
    implementation 'javax.servlet.jsp.jstl:jstl:1.2'
    implementation 'javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api:1.2.1'
}

If you are creating maven based project then you can use the following pom.xml file:

<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.roytuts</groupId>
	<artifactId>google-pie-chart-jsp-servlet</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>at least 1.8</java.version>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.2</version>
		</dependency>
		
		<dependency>
			<groupId>org.apache.taglibs</groupId>
			<artifactId>taglibs-standard-impl</artifactId>
			<version>1.2.5</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>1.2.1</version>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
                <configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

The version of Tomcat I am using for this example is 9.0.39.

Chart Data

Then I am creating sample data for showing on Google Pie Chart. This file contains area-wise top seven countries in the world.

package com.roytuts.google.pie.chart.jsp.servlet.repo;

import java.util.ArrayList;
import java.util.List;

public final class PieChartRepo {

    private PieChartRepo() {

    }

    private static final List<KeyValue> pieDataList;

    static {
        pieDataList = new ArrayList<PieChartRepo.KeyValue>();
        pieDataList.add(new KeyValue("Russia", "17098242"));
        pieDataList.add(new KeyValue("Canada", "9984670"));
        pieDataList.add(new KeyValue("USA", "9826675"));
        pieDataList.add(new KeyValue("China", "9596961"));
        pieDataList.add(new KeyValue("Brazil", "8514877"));
        pieDataList.add(new KeyValue("Australia", "7741220"));
        pieDataList.add(new KeyValue("India", "3287263"));
    }

    public static List<KeyValue> getPieDataList() {
        return pieDataList;
    }

    public static class KeyValue {
        String key;
        String value;

        public KeyValue(String key, String value) {
            super();
            this.key = key;
            this.value = value;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "KeyValue [key=" + key + ", value=" + value + "]";
        }

    }

}

Request/Response Servlet

Now I am going to create a servlet which will forward the data to the JSP page. This servlet handles request and response for clients or end users.

package com.roytuts.google.pie.chart.jsp.servlet;

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

import javax.servlet.RequestDispatcher;
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 com.roytuts.google.pie.chart.jsp.servlet.repo.PieChartRepo;
import com.roytuts.google.pie.chart.jsp.servlet.repo.PieChartRepo.KeyValue;

@WebServlet("/PieChart")
public class PieChartServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public PieChartServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<KeyValue> pieDataList = PieChartRepo.getPieDataList();
        System.out.println("pieDataList: " + pieDataList);
        
        request.setAttribute("pieDataList", pieDataList);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/chart.jsp");
        requestDispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

}

View File

Create a view called chart.jsp, under src/main/webapp folder, which will render the Google Pie Chart along with the data from Servlet. In view you can initialize data to chart in two ways:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
<c:forEach items="${pieDataList}" var="entry">
[ '${entry.key}', ${entry.value} ],
</c:forEach>
]);

Or

var data = google.visualization.arrayToDataTable([
['Country', 'Area(square km)'],
<c:forEach items="${pieDataList}" var="entry">
[ '${entry.key}', ${entry.value} ],
</c:forEach>
]);

In the above code notice I simply iterate through list using JSTL and add the data to the Google Pie Chart.

package com.roytuts.google.pie.chart.jsp.servlet;

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

import javax.servlet.RequestDispatcher;
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 com.roytuts.google.pie.chart.jsp.servlet.repo.PieChartRepo;
import com.roytuts.google.pie.chart.jsp.servlet.repo.PieChartRepo.KeyValue;

@WebServlet("/PieChart")
public class PieChartServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public PieChartServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<KeyValue> pieDataList = PieChartRepo.getPieDataList();
        System.out.println("pieDataList: " + pieDataList);
        
        request.setAttribute("pieDataList", pieDataList);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/chart.jsp");
        requestDispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

}

Coding part is done and now let’s test the application.

Testing the Application

Deploy your application into Tomcat server. Hit the URL http://localhost:8080/google-pie-chart-jsp-servlet/PieChart in the browser, you will see the output as shown in the below image:

google pie chart using jsp servlet

Now you can mouse over any slice or legend to check the actual value for the particular country.

google pie chart using jsp servlet

Source Code

Download

8 Thoughts to “Google Chart using JSP, Servlet”

  1. Very useful and interesting. Thankyou for sharing this Great article

  2. ABCD

    [ ‘${entry.key}’, ${entry.value} ],
    in this part where is “entry”?? I mean how to Implement “entry”

    1. entry is the variable. var=”entry”.

  3. bhabani

    hi , i am not getting jar file to import in.webtuts.google.chart.data.PieChartData package . Can you please help.

    1. ooh sorry to say i thought that was a package which need to be exported from jars

  4. sandeep bhoite

    hey hi appreciate your work but uri for taglib is invalid

    1. sandeep bhoite

      how we can resolve this issue

      1. sandeep bhoite

        got solved this issue, sorry it was blunder by me jstl was incorrect ! there is dependency strictly get jstl 1.2

Leave a Comment