Google Pie Chart Using Spring

Pie Chart

This tutorial is about Google chart using spring framework. You may 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 pie chart using Spring Boot. This tutorial shows step by step how to build Google pie chart using Spring Boot and Thymeleaf technologies. It displays the data for area-wise top seven countries in pie chart.

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

Java 19, Spring Boot 3.1.3, Maven 3.8.5

Project Setup

Create maven based project in your favorite IDE or tool. The following pom.xml file can be used for your project:

<?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.roytuts</groupId>
	<artifactId>spring-google-pie-chart</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>19</maven.compiler.source>
		<maven.compiler.target>19</maven.compiler.target>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.3</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

I am using Thymeleaf for the front-end or User Interface where pie chart data will be displayed.

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.

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;
		}
	}

}

Service Class

The service class generally used to process any business related logics for the application.

@Service
public class PieChartService {

	public List<KeyValue> getPieChartData() {
		return PieChartDao.getPieDataList();
	}

}

Controller Class

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

@Controller
public class PieChartController {

	@Autowired
	private PieChartService pieChartService;

	@GetMapping("/piechart")
	public String pieChart(Model model) {
		List<KeyValue> pieDataList = pieChartService.getPieChartData();
		
		model.addAttribute("pieDataList", pieDataList);

		return "index";
	}

}

View File

Create a view called index.html under src/main/resources/templates directory which will render the Google Pie Chart along with the data from Spring Controller.

<html xmlns:th="http://www.thymeleaf.org">
<head>
<!--<meta http-equiv="Content-Type" content="text/html; charset=utf-8">-->
<title>Google Pie Chart using Spring</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" th:inline="javascript">
	//Load data from server
	var chartData = /*[[${pieDataList}]]*/'';
	
	//Load chart package
    google.charts.load('current', {'packages':['corechart']});
       
    // Set a callback to run when the Google Visualization API is loaded.
    google.charts.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', 'Country');
        data.addColumn('number', 'Area(square km)');
        /*for(i = 0; i < chartData.length; i++) {
            data.addRow([ chartData[i].key, Number(chartData[i].value) ]);
        }*/
        //Or
        chartData.forEach(c => data.addRow([ c.key, Number(c.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);
    }
</script>
</head>
<body>
    <div style="width: 600px;">
        <div id="chart_div"></div>
    </div>
</body>
</html>

Spring Boot Main Class

A class is having main method and @SpringBootApplication will be enough to deploy the application into embedded Tomcat server.

@SpringBootApplication
public class GPieChartApp {

	public static void main(String[] args) {
		SpringApplication.run(GPieChartApp.class, args);
	}

}

Testing the Pie Chart Application

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

google pie chart using spring

When you mouse hove on any particular slice, the slice will be highlighted with percentage data:

google pie chart in spring

Source Code

Download

2 thoughts on “Google Pie Chart Using Spring

Leave a Reply

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