Displaying dynamic charts in a web page (using JFreeChart & JSP)

This code snippet will tell you how to create a chart (using JFreeChart) on the fly and displaying it in a webpage.

getChart.jsp

< %@ page import="java.io.*" %>
< %@ page import="org.jfree.chart.JFreeChart" %>
< %@ page import="org.jfree.chart.ChartUtilities" %>

< %
 try
 {
 File image = File.createTempFile("image", "tmp");

 // Assume that we have the chart
 ChartUtilities.saveChartAsPNG(image, chart, 500, 300);

 FileInputStream fileInStream = new FileInputStream(image);
 OutputStream outStream = response.getOutputStream();   

 long fileLength;
 byte[] byteStream;

 fileLength = image.length();
 byteStream = new byte[(int)fileLength];
 fileInStream.read(byteStream, 0, (int)fileLength);

 response.setContentType("image/png");
 response.setContentLength((int)fileLength);
 response.setHeader("Cache-Control", 
     "no-store,no-cache, must-revalidate, post-check=0, pre-check=0");
 response.setHeader("Pragma", "no-cache");

 fileInStream.close();
 outStream.write(byteStream);
 outStream.flush();
 outStream.close();

 }
 catch (IOException e)
 {
 System.err.println("Problem occurred creating chart.");
 }

%>

How to use it in a webpage:

<img src="getChart.jsp" alt="Progress chart" />

We can make it more dynamic using various parameters. See the sample below.

<img src="getChart.jsp?type=bar&action=showProfits" alt="Progress chart" />

Useful links: creating charts using JFreeChart
Creating BarChart with custom colors using JFreeChart
Creating a 3D BarChart using JFreeChart
Creating Time Series charts using JFreeChart
Creating Pie Chart using JFreeChart (Using plot)
Creating Pie Chart using JFreeChart

About these ads