JFreeChart : Create Auto-Refreshing Pie Chart in Servlet dynamically
This post explains the step by step process of creating a pie chart in Servlet with values retrieved from mysql database and displaying i...

Add Jfreechart library to your Web Application
1. First and foremost download Jfreechart library from here.
2. I am using Apache Tomcat and Eclipse IDE to create a simple application to demonstrate pie chart creation.
From the downloaded folder, copy jfreechart-x.x.x.jar and jcommon-x.x.x.jar (x.x.x in the jar file name denotes the version of the library), and paste it in the tomcat/lib directory.
3. Create a "Dynamic Web Project" in Eclipse IDE. In this example, I have named it as 'PieChartExample'.
Now go to Project Explorer, right click on 'PieChartExample' -> Build Path -> Configure Build Path -> Add External Jars. Add jfreechart-x.x.x.jar and jcommon-x.x.x.jar files and click OK.
Now the setup is complete and is ready for programming.
Create Pie Chart in Servlet from database values
5. Identify the database that is going to feed the pie chart with values to represent. I have created a sample table called 'country_revenue' in mysql database, that consists of country based revenue details of a company. Here is the data contained in the sample database,
package com; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.BasicStroke; import java.awt.Color; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartRenderingInfo; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.entity.StandardEntityCollection; import org.jfree.data.jdbc.JDBCPieDataset; import java.io.OutputStream; import java.sql.SQLException; import java.sql.DriverManager; import java.sql.Connection; public class PieChartDemo extends HttpServlet { private static final long serialVersionUID = 1L; public PieChartDemo() { } protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); try { connection= DriverManager.getConnection("jdbc:mysql://localhost/databasename?user=yourusername&password=yourpassword&useUnicode=true&characterEncoding=utf-8"); } catch (SQLException e) { e.printStackTrace(); } }catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } JDBCPieDataset dataset = new JDBCPieDataset(connection); try { dataset.executeQuery("Select country,revenue From country_revenue order by revenue desc"); JFreeChart chart = ChartFactory.createPieChart ("Country - Revenue Chart", dataset, true, true, false); chart.setBorderPaint(Color.black); chart.setBorderStroke(new BasicStroke(10.0f)); chart.setBorderVisible(true); if (chart != null) { int width = 500; int height = 350; final ChartRenderingInfo info = new ChartRenderingInfo (new StandardEntityCollection()); response.setContentType("image/png"); OutputStream out=response.getOutputStream(); ChartUtilities.writeChartAsPNG(out, chart, width, height,info); } }catch (SQLException e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
<servlet> <servlet-name>PieChartDemo</servlet-name> <servlet-class>com.PieChartDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>PieChartDemo</servlet-name> <url-pattern>/chart</url-pattern> </servlet-mapping>
10. Now right click the servlet and using Run as -> Run on Server option, run the servlet to see the newly created pie chart.
Display pie chart in JSP page and auto-refresh it
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Pie Chart Demo</title> <script language="Javascript"> function refreshpage(){ document.forms.form1.submit(); } </script> </head> <body> <h1>JFreechart: Create Pie Chart Dynamically</h1> <%response.setIntHeader("Refresh",5);%> <form id="form1"> <img src="chart" width="600" height="400" border="0"/> <input type="button" onclick="refreshpage()" value="Refresh"/> </form> </body> </html>
response.setIntHeader("Refresh",5);
Thanks a lot...It solved my 2days of problems with JFree! Simple and Excellent!
ReplyDeleteMost Welcome!
DeleteHi I am sharad... When I do the above steps and when I run I get the following error:
Deletejava.lang.NullPointerException: A connection must be supplied.
org.jfree.data.jdbc.JDBCPieDataset.(JDBCPieDataset.java:119)
com.ViewsGraph.doGet(ViewsGraph.java:44)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Thank you so much Priya
DeleteHello,
Deletewere anyone able to copy/paste the code? it's not letting me
Hello,
Deletewere anyone able to copy/paste the code? it's not letting me
I have enabled copy on the code block. Please try now.
DeleteHi Priya. Can you help me out with an xml file instead of database.
ReplyDeleteHello Ani, You have to use the dataset reader from the package 'org.jfree.data.xml.DatasetReader' to read data from xml files and create a jfreechart out of it. Please have a look at this simple example,
Deletehttp://thinktibits.blogspot.in/2012/11/Convert-xml-to-pie-chart-JFreechart-Java-Example.html
Hope this helps!
Hi priya,
ReplyDeletei am trying to call jfreechart from href link.after click on link piechart is not display. i m using ajax calling. any changes is required in servlet file.plz help
Thanks
Post your code or upload your source code in dropbox and share the link. Without code, there is no possibility for debugging it!
Deletehere is the link : https://www.dropbox.com/sh/tsc441ciqr1t4co/pmMq5sO5IE
Deletehere is my final jsp page:
ReplyDeletehttps://www.dropbox.com/s/mys033rj64522b9/finalpageinjsp.bmp
is it possible to make this project in web technologies using servlet and jsp.
Hi Lokesh,
DeleteSorry I dint find time to go through your code. In this post, I have explained how to create and display charts with servlet and jsp. Try to implement this and integrate it in your project.
Thanks,
Priya
Hai priya,
ReplyDeleteNow i am facing problem to create the drill down chart... i need the better blog to refer..
Thanking you.
I download more than 5 Source code..All are enough to understand..
ReplyDeleteThanks a lot for sharing it...
Most Welcome!
Deletesir i am getting "JDBCPieDataset - unknown data type " Erorr. Help Me asap
ReplyDeleteCan you double check whether you have imported this class?
Deleteimport org.jfree.data.jdbc.JDBCPieDataset;
Hope this helps!
provide source code for Auto-Refreshing Bar Chart in Servlet dynamically using JFreeChart
DeleteHey Priya i am stuck with some thing from last 3 days, hope you can help me out.
ReplyDeleteAs yr graph has country by clicking on a particular country i may see cities for that country. how to send the click co-ordinates from jsp to action and map those co-ordinates on yr chart co-ordinates.. I hope my problem is clear to you
Thanks in Advance.
HI natarajan,
ReplyDeleteAdd this code it will work like a charm
PreparedStatement preparedStatement = connection.prepareStatement("Select country,revenue From country_revenue order by revenue desc");
ResultSet rs = preparedStatement.executeQuery();
DefaultPieDataset pieDataset = new DefaultPieDataset();
while(rs.next())
{
pieDataset.setValue(rs.getString(1),rs.getInt(2));
}
rs.close();
preparedStatement.close();
//dataset.executeQuery("Select id,revenue From country_revenue order by revenue desc");
JFreeChart chart = ChartFactory.createRingChart("Country - Revenue Chart", pieDataset, true,true, false);
Dear Priya, Thank U Sooo much. I was trying this for last 4 days. U solved it in a very simple way. Love U friend....
ReplyDeleteDear Priya, I Stuck at one place. According to your code, I am using img src="chart" width="600" height="400" border="1" for calling the servlet and displaying the image. But in that servlet, in the sql query for generating the graph, i need user entered "username". How can I get it? I am using Struts DynaValidatorForm. Please share the sample code if possible. Thanks.
ReplyDeleteHi I am using struts 2.0
ReplyDeleteIs it possible to run in Struts 2.0
Priya Please help me with this code
ReplyDeletethanx a lot !!! from this code.. i done my part of project
ReplyDeletehi madam i want to create bar chart same as pie chart which is given by u how can i ?
ReplyDeleteReally a good job and thank you so much
ReplyDeletehello priya
ReplyDeletei want to show revenue value in chart how can i???
please help me ...
my chart is not show on jsp error is a JDBCPieDataset - unknown data type
ReplyDeleteJDBCPieDataset - unknown data type
JDBCPieDataset - unknown data type
JDBCPieDataset - unknown data type
JDBCPieDataset - unknown data type
JDBCPieDataset - unknown data type
Hi.. I ran the program but in the browser the chart is not showing (but the page is getting refreshed).. Please help ....Thank you
ReplyDeleteHI priya ji,
ReplyDeleteThanks a lot for the post, nice and simple
Hi thank you for your help... I am getting a problem this code the pie chart is not generating while it's showing a page with project name and servlet name please help again I have to show my project today..thanks you .
ReplyDeletePlease say how to display the arraylist values in the piechart thery are using category dataset how to replace it,I have the results stored in arraylist now want to convert into chart
ReplyDelete