Google Chart using Spring

Introduction

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 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 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.

Prerequisites

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="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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>spring-google-chart</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<url>http://maven.apache.org</url>
	<properties>
		<java.version>1.8</java.version>
		<spring.version>4.1.6.RELEASE</spring.version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<!-- jstl -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>spring-google-chart</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.2</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

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.

package com.roytuts.spring.google.piechart.dao;
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).

package com.roytuts.spring.google.piechart.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.roytuts.spring.google.piechart.dao.PieChartDao;
import com.roytuts.spring.google.piechart.dao.PieChartDao.KeyValue;
@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.

package com.roytuts.spring.google.piechart.controller;
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;
import com.roytuts.spring.google.piechart.dao.PieChartDao.KeyValue;
import com.roytuts.spring.google.piechart.service.PieChartService;
@Controller
public class PieChartController {
	@Autowired
	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.

package com.roytuts.spring.google.piechart.config;
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.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
@Component
public class WebAppInitializer implements WebApplicationInitializer {
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(WebMvcConfig.class);
		context.setServletContext(servletContext);
		ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet",
				new DispatcherServlet(context));
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/");
	}
}

Spring MVC Configuration

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

package com.roytuts.spring.google.piechart.config;
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;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.roytuts.spring.google.piechart")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
	@Bean
	public ViewResolver getViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/");
		resolver.setSuffix(".jsp");
		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');
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.

The source code for index.jsp file.

<%@ 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"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google Pie Chart using Spring</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 = 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',
            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);
    }
</script>
</head>
<body>
    <div style="width: 600px;">
        <div id="chart_div"></div>
    </div>
</body>
</html>

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 *