We 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. This tutorial shows step by step so that we can understand how it happens. It displays the data for area-wise top seven countries in pie chart. You can also use other charts for other purposes. In this example I have used static sample data and the actual data should come from database or other sources. You can change the source of data as per your requirements.

If you have any query please feel free to leave a comment.

Prerequisites

JDK 1.6
Knowledge of JSP, Servlet
Apache Tomcat v7
Eclipse IDE
jstl-1.2.jar

Final Output

When Chart rendered on view

Google Chart API

When you mouse hover on Chart slices

Google Chart API

Now we will see how it happens step by step.

Step 1. Create the Dynamic Web Project in Eclipse IDE. The required project structure gets created in the IDE.

Step 2. Put the jstl jar file under WEB-INF/lib directory. This jstl jar is used for iteration, conditional statement check etc. in UI side on JSP page.

Step 3. Now modify deployment descriptor – web.xml. Remove evrything including <welcome-file-list/> from web.xml.

Step 4. Then we will create sample data for showing on Google Pie Chart. So create a class PieChartData.java as shown below. This file contains area-wise top seven countries in the world.

package in.webtuts.google.chart.data;

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

public class PieChartData {

    private static final List<KeyValue> pieDataList;

    static {
        pieDataList = new ArrayList<PieChartData.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;
        }

    }

}

 

Step 5. Now we will create a servlet which will forward the data to the jsp page.

package in.webtuts.google.chart.servlets;

import in.webtuts.google.chart.data.PieChartData;
import in.webtuts.google.chart.data.PieChartData.KeyValue;

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;

/**
 * Servlet implementation class PieChartServlet
 */
@WebServlet("/PieChartServlet")
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 = PieChartData.getPieDataList();
        request.setAttribute("pieDataList", pieDataList);
        RequestDispatcher requestDispatcher = request
                .getRequestDispatcher("/servlet.jsp");
        requestDispatcher.forward(request, response);
    }

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

}

 

Step 6. Create a view called servlet.jsp 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 look carefully we simply iterate through list using jstl and add the data to the Google Pie Chart.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google Chart - Servlet 3</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', {
        'packages' : [ 'corechart' ]
    });

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart() {

        // Create the data table.
        //var data = new google.visualization.DataTable();
        //data.addColumn('string', 'Topping');
        //data.addColumn('number', 'Slices');
        /*data.addRows([
                    <c:forEach items="${pieDataMap}" var="entry">
                        [ '${entry.key}', ${entry.value} ],
                    </c:forEach>
                    ]);*/        
        var data = google.visualization.arrayToDataTable([
                                                              ['Country', 'Area(square km)'],
                                                              <c:forEach items="${pieDataList}" var="entry">
                                                                  [ '${entry.key}', ${entry.value} ],
                                                              </c:forEach>
                                                        ]);

        // Set chart options
        var options = {
            'title' : 'Area-wise Top Seven Countries in the World', //title which will be shown right above the Google Pie Chart
            is3D : true, //render Google Pie Chart as 3D
            pieSliceText: 'label', //on mouse hover show label or name of the Country
            tooltip :  {showColorCode: true}, // whether to display color code for a Country on mouse hover
            'width' : 900, //width of the Google Pie Chart
            'height' : 500 //height of the Google Pie Chart
        };

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
</script>
</head>
<body>
    <div style="width: 600px;">
        <div id="chart_div"></div>
    </div>
</body>
</html>

 

Step 7. If everything is done please run the application and see yourself. Hit the URL http://<host>:<port>/<context-path>/PieChartServlet. For examplehttp://localhost:8080/google-chart/PieChartServlet

Thanks for your reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

2 thoughts on “Google Chart using JSP, Servlet

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

Leave a Reply

Your email address will not be published. Required fields are marked *