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.

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

Prerequisites

JDK 1.6
Knowledge of Spring, Java
Apache Tomcat v7
Eclipse IDE
Jars

Google Chart using Spring - jars

Final Output

When chart renders on the view

Google Chart API

When mouse hover happens on chart

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 all jar files under WEB-INF/lib directory.

Step 3. Now modify deployment descriptor – web.xml under WEB-INF directory. Paste the below code in your web.xml file.

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>     
    <!-- spring mvc dispatcher servlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>piechart.html</welcome-file>
    </welcome-file-list>

Step 4. Create Spring DAO. This data access layer retrieves the required data for chart to display.

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

package in.webtuts.google.chart.spring.daos;

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

import java.util.List;

public interface PieChartDao {

    List<KeyValue> getPieChartData();

}
package in.webtuts.google.chart.spring.daos;

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

import java.util.List;

public class PieChartDaoImpl implements PieChartDao {

    @Override
    public List<KeyValue> getPieChartData() {
        return PieChartData.getPieDataList();
    }

}

 

Step 5. Create Spring Service

package in.webtuts.google.chart.spring.services;

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

import java.util.List;

public interface PieChartService {

    List<KeyValue> getPieChartData();

}
package in.webtuts.google.chart.spring.services;

import in.webtuts.google.chart.data.PieChartData.KeyValue;
import in.webtuts.google.chart.spring.daos.PieChartDao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

public class PieChartServiceImpl implements PieChartService {

    @Autowired
    private PieChartDao pieChartDao;

    public void setPieChartDao(PieChartDao pieChartDao) {
        this.pieChartDao = pieChartDao;
    }

    @Override
    public List<KeyValue> getPieChartData() {
        return pieChartDao.getPieChartData();
    }

}

 

Step 6. Create Spring Controller

package in.webtuts.google.chart.spring.controllers;

import java.util.List;

import in.webtuts.google.chart.data.PieChartData.KeyValue;
import in.webtuts.google.chart.spring.services.PieChartService;

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;

@Controller
@RequestMapping("/piechart")
public class PieChartController {

    @Autowired
    private PieChartService pieChartService;
    
    

    @RequestMapping(method = RequestMethod.GET)
    public String springMVC(ModelMap modelMap) {
        List<KeyValue> pieDataList = pieChartService.getPieChartData();
        modelMap.addAttribute("pieDataList", pieDataList);
        return "spring";
    }

}

 

Step 7. Create dispatcher-servlet.xml with the below code under WEB-INF directory

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan
        base-package="in.webtuts.google.chart.spring.controllers, in.webtuts.google.chart.spring.daos, in.webtuts.google.chart.spring.services"></context:component-scan>
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

 

Step 8. Create applicationContext.xml with the below code under WEB-INF directory

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- get benefit of annotations -->
    <context:annotation-config></context:annotation-config>

    <!-- declare spring DAO -->
    <bean id="pieChartDao" class="in.webtuts.google.chart.spring.daos.PieChartDaoImpl"></bean>

    <!-- declare spring Service -->
    <bean id="pieChartService"
        class="in.webtuts.google.chart.spring.services.PieChartServiceImpl">
        <property name="pieChartDao" ref="pieChartDao"></property>
    </bean>
</beans>

 

Step 9. 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 10. Create a view called spring.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.

<%@ 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 = 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>

 

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

Download source code google-chart

Thanks for your reading.

Tags:

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

1 thought on “Google Chart using Spring

  1. Respected Sir
    I see above code for generate pie chart with static values .
    I am new in Spring mvc+jsp+ajax+jquery.
    I want code how to display database value to bar chat in jsp spring mvc.
    I am expected correct code in your web site.

    Thanking you.

  2. I have everything working except this part of the code:

    ———————————————————–
    // Create the data table.
    var data = google.visualization.arrayToDataTable([
    [‘Country’, ‘Area(square km)’],

    [ ‘${entry.key}’, ${entry.value} ],

    ]);
    ———————————————————–
    I change it with fixed values like this part of code just to ake sure everything working and it has shown up:
    ———————————————————–
    var data = google.visualization.arrayToDataTable([
    [‘Element’, ‘Density’, { role: ‘style’ }],
    [‘Copper’, 8.94, ‘#b87333’, ],
    [‘Silver’, 10.49, ‘silver’],
    [‘Gold’, 19.30, ‘gold’],
    [‘Platinum’, 21.45, ‘color: #e5e4e2’ ]
    ]);
    ———————————————————–
    So, i need some explanation maybe something is missing.

    1. That’s welcome and you can get my email at Contact page link; but first try to make the example work whatever there in my tutorial. And once it works then try to change according to your requirements.

  3. I am also getting the same error while iterating the list
    ‘${entry.key}’,${entry.value}

    Please help me to resolve this,
    All the jars are correct, xml files are in place.

Leave a Reply

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