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 JSF. 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 JSF, Java
Apache Tomcat v7
Eclipse IDE
javax.faces.jar

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 the javax.faces.jar file under WEB-INF/lib directory. This javax.faces.jar is used for JSF framework.

Step 3. Now modify deployment descriptor – web.xml. Paste the below code in your web.xml file.

<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>jsf.jsf</welcome-file>
</welcome-file-list>

 

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 JSF Managed Bean which will display data in the appropriate view.

package in.webtuts.google.chart.jsf.mbeans;

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

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class PieChartMBean implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

private String pieChartData;
private List<KeyValue> pieDataList;

public PieChartMBean() {
this.pieDataList = PieChartData.getPieDataList();
}

public String getPieChartData() {
if (pieChartData == null || pieChartData.trim().length() <= 0) {
populateData();
}
return pieChartData;
}

private void populateData() {
StringBuilder stringBuilder = new StringBuilder();
for (KeyValue pieData : pieDataList) {
stringBuilder.append("[");
stringBuilder.append("'");
stringBuilder.append(pieData.getKey());
stringBuilder.append("'");
stringBuilder.append(",");
stringBuilder.append(pieData.getValue());
stringBuilder.append("]");
stringBuilder.append(",");
}
pieChartData = stringBuilder.toString().substring(0,
stringBuilder.toString().length() - 1);
}
}

 

Step 6. Create a view called jsf.xhtml which will render the Google Pie Chart along with the data from JSF Managed Bean. 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([
#{pieChartMBean.pieChartData}
]);

or

var data = google.visualization.arrayToDataTable([
['Country', 'Area(square km)'],
#{pieChartMBean.pieChartData}
]);

In the above code look carefully we simply call the backing bean property and add the data to the Google Pie Chart.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Google Chart - JSF 2</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)' ],
#{pieChartMBean.pieChartData}
]);

// 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>
</h:head>
<h:body>
<div style="width: 600px;">
<div id="chart_div"></div>
</div>
</h:body>
</html>

 

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

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 | Email Me

0 thoughts on “Google Chart using JSF

  1. Hi Soumitra,

    This is very good example, But here instated of using tag can you tell me any tag is there.

    I’m pacing some problem using div tag because here div tag id is not possible to update
    using JSF Technology (Framefaces, richfaces)

    EX:

    // Load the Visualization API and the piechart package.
    google.load(‘visualization’, ‘1.0’, {
    ‘packages’ : [ ‘corechart’, ‘table’ ]
    });

    // 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() {
    var data1 = google.visualization.arrayToDataTable(
    #{cnsSMSReportbyEventsBean.graphicEventNames}
    );
    var options1 = {
    colors: [‘green’, ‘red’, ‘blue’, ‘orange’, ‘yellow’],
    legend: { position: ‘right’, alignment: ‘start’, maxLines: 50 },
    bar: { groupWidth: ‘75%’ },
    isStacked: true,
    vAxis: {title: ‘Count’, titleTextStyle: {color: ‘black’}},
    hAxis: {title: ‘Event Names’, titleTextStyle: {color: ‘black’}}
    };

    var chart1 = new google.visualization.ColumnChart(document.getElementById(‘chart_divd’));
    chart1.draw(data1, options1);
    }

    =========================================

    SMS
    Report by Event Names

    =====================================================================

    ===================================================
    whenever we click Search button it will display the graph chart but here after click search button and refresh the then it will display the graph. so here div tag will not be updated. Please tell now instated of using div tag any tag can we use? without refresh page.

    +Seshadri
    7899358262

Leave a Reply

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