Tuesday, April 7, 2009 0 comments

JFreeChart For The Web


Ever needed to create a JFreeChart and display it in your web application?Well people i was in need of the same and after searching in vain i finally was able to put together a solution and thought i should share it with you all which will save you a considerable amount of development time.

 

 

1. Create a jsp xxx.jsp and include the following line within the jsp;

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

 

2. Then you need to write your servlet code. Include the following code snippet in your servlet which will

    create a temp image file in your server and use that to stream it to your response. Note that i have created a

    simple bar chart in the following code snippet,but you can change it with what ever chart that you are

    working with.

 

public static void createBarChart(String chartTitle, String xAxisName,

String yAxisName, DefaultCategoryDataset dataSet,

HttpServletRequest request, HttpServletResponse response) {

try {

// NOTE : I have filled in the Dataset with a DefaultCategoryDataset

// data set

JFreeChart chart = ChartFactory.createBarChart(chartTitle,

xAxisName, yAxisName, dataSet, PlotOrientation.VERTICAL,

false, true, false);

File image = File.createTempFile("image", "tmp");

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) {

}

}

 

 

Thats it guys. Include the following in your servlet code and your good to go with JFreeChartsin you web application. Hope this helps.

 


 
;