Pages Navigation Menu

Coding is much easier than you think

Auto-Refreshing Pie Chart/Bar Chart in Servlet dynamically using JFreeChart

 
In this post, we’ll learn to create a pie chart using JFreeChart that can be returned as an image from a servlet. Here, I have created the pie chart using the values retrieved from database and display it in JSP. In order to sync the pie chart with values from a database that is frequently updated, I have written auto-refresh script which refresh the page automatically at regular intervals.
 
piechart-using-jfreechart
 

Recommended reading

 

Libraries required :

 
jfreechart-x.x.x.jar
jcommon-x.x.x.jar
Download Jfreechart library from here.
 
Now let us create a sample table called ‘air_pollution’ in oracle database, that consists of the factors which causes air pollution and its percentage of emission.

create table air_pollution(source varchar(50), percentage int)

 
Here is the data contained in the above table
 
oracle db Jfree chart
 
Now Create a New Dynamic Web Project in eclipse with following folder structure
 
Pie Chart demo
 

Servlet

 
File : PieChartServlet.java

package com.simplecodestuffs.action;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.jdbc.JDBCPieDataset;

import com.simplecodestuffs.jdbc.DataAccessObject;

public class PieChartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Connection dbConnection = null;

	public PieChartServlet() {
		dbConnection = DataAccessObject.getConnection();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		JDBCPieDataset dataSet = new JDBCPieDataset(dbConnection);

		try {
		dataSet.executeQuery("SELECT SOURCE,PERCENTAGE FROM AIR_POLLUTION ORDER BY PERCENTAGE");
		JFreeChart chart = ChartFactory.createPieChart(
		 "Source of Air Pollution ", // Title
	         dataSet,                    // Data
	         true,                       // Display the legend
	         true,                       // Display tool tips
	         false                       // No URLs
		 );
			
		if (chart != null) {
         		chart.setBorderVisible(true);
			int width = 600;
			int height = 400;
			response.setContentType("image/jpeg");
			OutputStream out = response.getOutputStream();
			ChartUtilities.writeChartAsJPEG(out, chart, width, height);
		}
		}
		catch (SQLException e) {
			System.err.println(e.getMessage());
		}
	}
}

 

Recommended reading:

 
Here Jfreechart’s JDBCPieDataSet method is used to retrieve data from database and createPieChart() method creates the pie chart with the populated dataset. writeChartAsJPEG() method is responsible for rendering the image in jpeg format.

Note :
If you want the pie chart generated to be in PNG format, then writeChartAsPNG() method can be used.
 

DAO Class

 
Create utility class which connect to database Using Oracle JDBC driver

package com.simplecodestuffs.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class DataAccessObject {
	private static Connection connection = null;

	public static Connection getConnection() {
		if (connection != null)
			return connection;
		else {
			// Store the database URL in a string
		String serverName = "127.0.0.1";
		String portNumber = "1521";
		String sid = "XE";
		String dbUrl = "jdbc:oracle:thin:@" + serverName + ":" + portNumber
				+ ":" + sid;
		try {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		// set the url, username and password for the database
		connection = DriverManager.getConnection(dbUrl, "system", "admin");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	}
}

 

Web.xml

Make sure you have done servlet mapping properly in web.xml file as shown below
 


   PieChartServlet
   com.simplecodestuffs.action.PieChartServlet


   PieChartServlet
   /displayChart


   pieChart.jsp

 

Auto refresh Jsp

 





Pie Chart Demo



	

Create Pie Chart Dynamically using JFreechart

<% response.setIntHeader("Refresh", 10); %>

 

In Jsp, servlet is called via img tag’s src attribute, this triggers the servlet and render the image on jsp.

To automate the page refreshing process, the following code is used

response.setIntHeader("Refresh",10);

It will reload the current request after the given amount of seconds, as if you’re pressing F5. Here I set the time interval to 10 seconds, So the page will refresh and render updated data from database for every 10 seconds, this value can be set based on your requirement.

 
Note :
This automatic refreshing can cause a considerable performance impact since it hits database for every 10 second, so it is a good practice to have a ‘Refresh’ button to enable the end-users to decide on when to refresh the page.
 

Demo

 
Now right click on the project name and select Run As –> Run on Server.
 
jFree chart using servlet
 
Similarly to Create bar chart, replace the doGet method in the Servlet with the following code.

public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	JDBCCategoryDataset dataset = new JDBCCategoryDataset(dbConnection);
	
	try {
	dataset.executeQuery("SELECT SOURCE,PERCENTAGE FROM AIR_POLLUTION ORDER BY PERCENTAGE");
	
	JFreeChart chart = ChartFactory.createBarChart(
               "Source of Air Pollution", "Scource", "Percentage",
               dataset, PlotOrientation.VERTICAL, false, true, false);
               chart.setBorderVisible(true);
	
	if (chart != null) {
		int width = 600;
		int height = 400;
		response.setContentType("image/jpeg");
		OutputStream out = response.getOutputStream();
		ChartUtilities.writeChartAsJPEG(out, chart, width, height);
	}
	}
	catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

 

Demo

 
Bar chart – demo
 
Bar Chart Using JfreeChart
 
download
 

Reference

 

4 Comments

  1. i have changed the oracle database from your code to mysql:
    DataAccessObject.java

    package com.simplecodestuffs.jdbc;

    import java.sql.Connection;
    import java.sql.DriverManager;

    public class DataAccessObject
    {
    private static Connection connection = null;
    static String dbUrl = “jdbc:mysql://localhost:3306/test”;
    static String USER = “root”;
    static String PASS = “root”;

    public static Connection getConnection()
    {
    // Store the database URL in a string
    //String serverName = “127.0.0.1”;

    try {
    Class.forName(“com.mysql.jdbc.Driver”);
    if(connection == null)
    {
    connection = DriverManager.getConnection(dbUrl, “USER”, “PASS”);
    }
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    return connection;
    }

    }

  2. hello , this code did a great job . But the problem is image is not able to display. Please refer the image https://uploads.disquscdn.com/images/9abb5d712809ee07700421bbfb3cff159279fee36f22f9412422bb0596ab64c3.jpg

  3. hello , this code did a great job . But the problem is image is not able to display. Please refer the image

  4. Hi Jamil, I tried your cod and its perfectly working for me,But my requirement is slightly different–I want my chart to be updated when the button clicks,—is it possible? can you help me out