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...
https://www.programming-free.com/2012/07/jfreechart-create-auto-refreshing-pie.html
This post explains the step by step process of creating a pie chart in Servlet with values retrieved from mysql database and displaying it in an auto-refreshing JSP page with an example using Jfreechart library. It is always good to represent statistical data in graphical format instead of just displaying it in rows and columns of a table, for better understanding and easy interpretation. Pie Chart is one way of producing analyzable data in graphical representation. In Java, you can draw a pie chart using methods from Graphics class of java.awt package. But it is quite tedious to design your own class for the creation of pie charts and populating it with appropriate data with the generic Graphics class of the Java API. Still, if you choose to draw your own pie chart you can have a look at this.
There are many open source Java libraries available for instant creation of pie chart in your Java application, among which Jfreechart is easiest and the most widely used one. In this post I am going to provide a simple example for creating pie chart using Jfreechart to represent statistical data. When I say statistical data, in most of the cases it comes from a database. Here, I am going to retrieve data from mysql database, create pie charts in a Servlet and display it using JSP. I am using JSP to display the created pie chart not only to keep the presentation aside from the logic but mainly to provide auto-refreshing pie charts in order to keep the data in the pie chart and database in sync.
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
4. Create a Servlet in your web application. I have created a servlet named 'PieChartDemo' under the package 'com'.
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,
+------+---------+---------+
| id | country | revenue |
+------+---------+---------+
| C001 | US | 100000 |
| C002 | UK | 90000 |
| C003 | RUSSIA | 34000 |
| C004 | CHINA | 90500 |
| C005 | INDIA | 340000 |
+------+---------+---------+
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 { } }
In the above code, we have created connection to the database with the DriverManager.getConnection method. Do not forget to replace the parameters of this method with your database name, username and password. Jfreechart provides JDBCPieDataSet method to retrieve appropriate data from database and createPieChart() method creates the pie chart with the populated dataset. writeChartAsPNG() is the method that is responsible for rendering the image in png format. Always set the content type to the appropriate image format before trying to write it with the writeChartAs method. Here the content type is set as 'image/png' since I have used writeChartAsPNG() method. You can also use writeChartAsJPEG() method to render a JPEG image.
<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.
As you see in the above image, pie chart is generated that represents country based revenue of a company. But, this page is static since servlet itself is static in nature. Though we have fetched values from database, it does not display the current or updated data from the database. For displaying pie chart with values from a database that is frequently updated, you need to recall the servlet. In order to achieve this I suggest you to use a JSP page to display the servlet and refresh it automatically at regular intervals.
Display pie chart in JSP page and auto-refresh it
11. Create a JSP page and paste the following code in 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>
In the above code, servlet is called from the img tag's src attribute. This triggers the servlet whenever the image is rendered on the page. To automate the page refreshing process,
response.setIntHeader("Refresh",5);
is used which sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds. Here the time interval is 5 seconds, which means the page will refresh and render updated data from database for every 5 seconds.
Output:
You can set the time interval for page refresh based on how often your database gets updated, but never set it to less than a second to avoid over CPU load. This automatic refreshing can also be achieved using Javascript or HTML page refresh. But it is a good practice to have a 'Refresh' button to enable the end-users to decide on when to refresh the page.
I hope this post helped you to create your own pie chart in your web application using JFreeChart. Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.
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