Google Chart using Spring


This tutorial is about Google chart using spring framework. 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 for more information.

You can integrate Google chart with any server side technology but here I will show you how to integrate Google chart using Spring MVC. 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.


JDK 1.8
Knowledge of Spring, Java
Apache Tomcat 8.5
Eclipse IDE
Maven 3.6.0

Final Result

The pie chart renders on web page by hitting the URL http://localhost:8080/spring-google-chart/piechart

Google Chart API

When mouse hover happens on chart

Google Chart API

Example with Source Code

Now we will see how it happens step by step.

Creating Project

Create maven based webapp in Eclipse IDE with Group Id: com.roytuts and Artifact Id: spring-google-chart. The required project structure gets created in the IDE.

google chart using spring

Updating pom.xml

Update the maven build file pom.xml to have the following dependencies for the project:

<project xmlns=""
		<!-- Spring -->
		<!-- jstl -->

Notice we have configure <failOnMissingWebXml> tag to set value false, because we are building annotation based Spring MVC application. So we are not going to create any XML file. Therefore we will configure such things using Java class.

Creating DAO Class

Create Spring DAO. This data access layer retrieves the required data for chart to display. This file contains area-wise top seven countries in the world.

The actual data should come from database or other persistent storage.

import java.util.ArrayList;
import java.util.List;
public class PieChartDao {
	private static final List<KeyValue> pieDataList;
	static {
		pieDataList = new ArrayList<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) {
			this.key = key;
			this.value = value;
		public String getKey() {
			return key;
		public String getValue() {
			return value;

Creating Service Class

Create Spring Service class to process your business(if any).

import java.util.List;
import org.springframework.stereotype.Service;
public class PieChartService {
	public List<KeyValue> getPieChartData() {
		return PieChartDao.getPieDataList();

Creating Controller Class

Create Spring Controller class to handle request/response coming from clients.

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
public class PieChartController {
	private PieChartService pieChartService;
	@RequestMapping(value = "/piechart", method = RequestMethod.GET)
	public String springMVC(ModelMap modelMap) {
		List<KeyValue> pieDataList = pieChartService.getPieChartData();
		modelMap.addAttribute("pieDataList", pieDataList);
		return "index";

Dispatcher Servlet

We are building annotation based application, so we will not create any XML file for our application and we will configure such things using Java class. So we will create a class that extends WebApplicationInitializer to configure DispatcherServlet.

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
				new DispatcherServlet(context));

Spring MVC Configuration

Create a configuration class for configuring Spring MVC, view resolver, scan Spring Annotated classes, such as, @Service, @Controller etc.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@ComponentScan(basePackages = "")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
	public ViewResolver getViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		return resolver;

Creating View File

Create a view called index.jsp under webapp directory which will render the Google Pie Chart along with the data from Spring Controller. 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');
	<c:forEach items="${pieDataList}" var="entry">
		[ '${entry.key}', ${entry.value} ],


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

In the above code look carefully we simply iterate through list using jstl and add the data to the Google Pie Chart.

The source code for index.jsp file.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@taglib prefix="c" uri=""%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google Pie Chart using Spring</title>
<script type="text/javascript" src=""></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.
    // 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 = google.visualization.arrayToDataTable([
                                                              ['Country', 'Area(square km)'],
                                                              <c:forEach items="${pieDataList}" var="entry">
                                                                  [ '${entry.key}', ${entry.value} ],
        // Set chart options
        var options = {
            'title' : 'Area-wise Top Seven Countries in the World',
            is3D : true,
            pieSliceText: 'label',
            tooltip :  {showColorCode: true},
            'width' : 900,
            'height' : 500
        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    <div style="width: 600px;">
        <div id="chart_div"></div>

Testing the Application

If everything is done please run the application. Hit the URL http://<host>:<port>/<context-path>/piechart. For example  http://localhost:8080/spring-google-chart/piechart

google chart using spring

Source Code

download source code

Thanks for your reading.

2 thoughts on “Google Chart using Spring

Leave a Reply

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