using JFreeChart with JSP

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
NY
Posts: 3
Joined: Tue Mar 20, 2007 7:35 am

Post by NY » Wed Mar 21, 2007 10:05 am

david.gilbert wrote:The rotating pie chart works in Swing because the ChartPanel class picks up ChartChangeEvent notifications (which are triggered by a chain of events that starts when the dataset is modified) and repaints the chart. You can't do the same thing in a web app.
Thanks a lot for this info....bt can u pls also tell me how to do this using an applet.......

AggressiveFish
Posts: 10
Joined: Wed Apr 18, 2007 8:37 pm

How to convert from this to JSP

Post by AggressiveFish » Thu Apr 19, 2007 8:19 pm

Here is the example I wish to convert to a JSP document instead. Anyone got any helpful advice on how to do? Thanks.

www[dot]informit[dot]com/guides/printerfriendly.asp?g=java&seqNum=74&rl=1

[bubble][bubble]
AF

bieira
Posts: 2
Joined: Tue May 08, 2007 5:33 pm

help

Post by bieira » Tue May 08, 2007 5:42 pm

I need help!!!


Is possivel to someone get me an example to generate a chart with struts…
that function in tomcat.... i need for one project..

thanks ... sorry my english ;)

bztom33
Posts: 35
Joined: Tue Jul 11, 2006 10:35 pm

Post by bztom33 » Sat Sep 15, 2007 12:14 am

Is it possible to generate multiple charts using a loop with out creating a unique chartViewer for each charts? The number of charts generated is dynamic. It can be 2,4,5 or 10.

When I tried, it always ends up with the same last parameters chart.

m_dieu
Posts: 15
Joined: Thu Sep 27, 2007 12:33 pm

i dont see the chart on the jsp :(

Post by m_dieu » Thu Sep 27, 2007 5:08 pm

Hey everybody,

I'm in touch with the lib since yesterday and I tried to copy the example placed by psupa (see Site 1 or quote below).
Now my problem is that I can't see the image. Obviously I'm not the only one with this problem after reading the other messages but I can't solve it by myself :(

The answer should be that I have to embed the image and not only the link but I don't know how...

My JSP-Code:

Code: Select all

<html>
<head>
</head>
<body>

<%String chartViewer = myChart.getChartViewer(request, response);%> 
<img src="<%=chartViewer%>" border=0 usemap="#imageMap">
(...)

</body>
</html>

The resulting HTML-Code:

Code: Select all

(...)
<body>

(...)

<map id="imageMap" name="imageMap">
<area shape="poly" coords="200,85,228,79,257,74,288,72,320,71,320,163,320,163" onMouseOver="return overlib('Dec = 15,913');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Dec&pieIndex=0"/>
<area shape="poly" coords="123,119,138,109,156,100,177,92,200,85,320,163,320,163" onMouseOver="return overlib('Nov = 14,316');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Nov&pieIndex=0"/>

<area shape="poly" coords="95,164,97,152,102,141,110,130,123,119,320,163,320,163" onMouseOver="return overlib('Oct = 14,43');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Oct&pieIndex=0"/>
<area shape="poly" coords="143,220,123,208,108,194,98,179,95,164,320,163,320,163" onMouseOver="return overlib('Sep = 18,474');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Sep&pieIndex=0"/>
<area shape="poly" coords="249,251,218,246,190,239,165,230,143,220,320,163,320,163" onMouseOver="return overlib('Aug = 16,525');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Aug&pieIndex=0"/>
<area shape="poly" coords="386,252,351,255,317,256,282,254,249,251,320,163,320,163" onMouseOver="return overlib('Jul = 17,524');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Jul&pieIndex=0"/>
<area shape="poly" coords="503,217,479,228,451,238,420,246,386,252,320,163,320,163" onMouseOver="return overlib('Jun = 18,57');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Jun&pieIndex=0"/>
<area shape="poly" coords="540,181,534,190,526,199,516,208,503,217,320,163,320,163" onMouseOver="return overlib('May = 12,057');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=May&pieIndex=0"/>
<area shape="poly" coords="540,145,543,154,544,163,543,172,540,181,320,163,320,163" onMouseOver="return overlib('Apr = 10,91');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Apr&pieIndex=0"/>
<area shape="poly" coords="491,103,508,113,522,123,532,134,540,145,320,163,320,163" onMouseOver="return overlib('Mar = 14,239');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Mar&pieIndex=0"/>
<area shape="poly" coords="411,79,454,89,491,103,320,163,320,163" onMouseOver="return overlib('Feb = 12,686');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Feb&pieIndex=0"/>
<area shape="poly" coords="320,71,366,73,411,79,320,163,320,163" onMouseOver="return overlib('Jan = 11,854');" onMouseOut="return nd();" href="Bar3DDemo.jsp?section=Jan&pieIndex=0"/>
</map>

(....)
<img src="http:/localhost:7001/servlet/ChartViewerServlet" border=0 usemap="#imageMap">
(...)
Can anybody help me?!
The rest is similar to psupas example!
psupa wrote:I used to be in this situation. Found many posted but difficult to follow, may be due to not enough knowledge or whatever. Finally, I got it works by trial and error and with help from person in this original posted, "pmarsollier".

I'm not aim to teach, but would like to guide for newbie.

1. Create ChartViewer servlet (ChartViewer.java)

Code: Select all

/**
 *
 * Need to produce some chart prior to this action call in a Java bean
 * Need a session attribute named "chartImage";
 * 
 */

package myapp.webwork.servlets;

import java.io.*;
import java.awt.image.*; 
import javax.servlet.*;
import javax.servlet.http.*;
import com.keypoint.PngEncoder;

public class ChartViewer extends HttpServlet {

  public void init() throws ServletException { 
  } 

  //Process the HTTP Get request 
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
         throws ServletException, IOException { 

	// get the chart from session
	HttpSession session = request.getSession(); 
	BufferedImage chartImage = (BufferedImage) session.getAttribute("chartImage"); 

	// set the content type so the browser can see this as a picture
	response.setContentType("image/png");

	// send the picture
	PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);
	response.getOutputStream().write(encoder.pngEncode());
	
  } 

(...)

[/code]

m_dieu
Posts: 15
Joined: Thu Sep 27, 2007 12:33 pm

Post by m_dieu » Fri Sep 28, 2007 9:35 am

OK, I found my problem.

I don't know why but after creating my BufferedImage and place it in the session a new session is created and so I cant find my "old" object :(

Any ideas why this can happen?

m_dieu
Posts: 15
Joined: Thu Sep 27, 2007 12:33 pm

Post by m_dieu » Fri Sep 28, 2007 10:35 am

...and solve it.

Anybody who might have a similar problem:
response.encodeURL in the JSP is the answer.

bztom33
Posts: 35
Joined: Tue Jul 11, 2006 10:35 pm

Post by bztom33 » Tue Oct 02, 2007 11:17 pm

I've similar problem. Is it possible to see your JSP file setup?

bztom33
Posts: 35
Joined: Tue Jul 11, 2006 10:35 pm

Post by bztom33 » Wed Oct 03, 2007 1:21 am

Does anyone get the following to work in a loop? It always end up with the same image. I verified that different datasets are being passed to the java bean.

Code: Select all

<html>
<head>
<title>Pie Chart Demo</title>
</head>

<jsp:useBean id="myChart" scope="session" class="myapp.webwork.beans.Pie3DDemo" />

<body>
<h2>Pie Chart Demo</h2>

loop foreach different dataset generate a different chart image.
{

<%String chartViewer = myChart.getChartViewer(request, response);%>
<img src="<%=chartViewer%>" border=0 usemap="#imageMap">

 }

</body>
</html> 

jwenting
Posts: 157
Joined: Sat Jul 15, 2006 7:46 am

Post by jwenting » Wed Oct 03, 2007 8:05 am

nothing different is being passed there... Not that it's valid code of course.

bztom33
Posts: 35
Joined: Tue Jul 11, 2006 10:35 pm

Post by bztom33 » Wed Oct 03, 2007 5:28 pm

Here is a pseudo code:

Code: Select all

<%
while (dataset.next()) {

String chartViewer = myChart.getChartViewer(request, response,dataset);
%>
<img src="<%=chartViewer%>" border=0 usemap="#imageMap"> 
<%
}
%>


Angeline
Posts: 2
Joined: Wed Jan 02, 2008 7:35 am
Location: Malaysia

Post by Angeline » Wed Jan 02, 2008 8:23 am

I got this error

Code: Select all

org.apache.jasper.JasperException: /admin/pages/Pie3DDemo.jsp(6,0) The value for the useBean class attribute jitterviewer.Pie3DDemo is invalid.
	org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
May i know this is wat error?

kiranc_nair
Posts: 1
Joined: Fri Apr 04, 2008 6:02 am

Display chart dynamically on the page using JPEGImageEncoder

Post by kiranc_nair » Fri Apr 04, 2008 6:14 am

Display the JFreeChart dynamically in a JSP
//Author: Kiran C Nair
//e-mail: kirancnair@gmail.com

This code is used to display the CHART dynamically in a JSP.
Main Advantages:
1. It does not requires the buffered image to be sotred or converted into an image file before being displayed.
2. The changes that occur are dynamically reflected on the chart.
3. No need to use struts or other framewrks.

Disadvantage:
1. When we use the encoder.encode() function the whole JSP gets encoded and nothing else can be displayed.


The Sample JSP Page

Code: Select all

<%@ page import="java.util.ArrayList"%>
<%@ page import="org.jfree.chart.*"%>
<%@ page import="org.jfree.chart.plot.*"%>
<%@ page import="org.jfree.chart.renderer.xy.XYItemRenderer"%>
<%@ page import="org.jfree.chart.renderer.xy.XYLineAndShapeRenderer"%>
<%@ page import="org.jfree.ui.RectangleInsets"%>
<%@ page import="java.awt.Color"%>
<%@ page import="org.jfree.data.xy.*"%>
<%@ page import="org.jfree.chart.entity.StandardEntityCollection"%>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="java.io.OutputStream"%>
<%@ page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%>
<%@ page import="com.sun.image.codec.jpeg.JPEGCodec"%>
<%@ page import="org.jfree.data.time.Month"%>
<%@ page import="org.jfree.data.time.TimeSeries"%>
<%@ page import="org.jfree.data.time.TimeSeriesCollection"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="org.jfree.chart.axis.DateAxis" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%

try{
	TimeSeries s1 = new TimeSeries("Sample Time series", Month.class);
	double d1 = 171.1;
	double d2 = 181.8;
	double d3 = 167.3;
    double d4 = 153.8;
    double d5 = 167.6;
    double d6 = 158.8;
    double d7 = 148.3;
    double davg = ((d1+d2+d3+d4+d5+d6+d7)/7);
    System.out.println("the average value of the datas are:" + davg);

    TimeSeries s2 = new TimeSeries("Sample Time series", Month.class);
    double c1 = 171.1;
	double c2 = 181.8;
	double c3 = 167.3;
    double c4 = 153.8;
    double c5 = 167.6;
    double c6 = 158.8;
    double c7 = 148.3;
    double cavg = ((d1+d2+d3+d4+d5+d6+d7)/7);
    System.out.println("the average value of the datas are:" + davg);
    
    s1.add(new Month(1,2007), 171.1);
	s1.add(new Month(2,2007), d2);
	s1.add(new Month(3,2007), 167.3);
	s1.add(new Month(4,2007), 153.8);
	s1.add(new Month(5,2007), 167.6);
	s1.add(new Month(6,2007), 158.8);
	s1.add(new Month(7,2007), 148.3);
	
	s2.add(new Month(1,2007), 171.1);
	s2.add(new Month(2,2007), d2);
	s2.add(new Month(3,2007), 167.3);
	s2.add(new Month(4,2007), 153.8);
	s2.add(new Month(5,2007), 167.6);
	s2.add(new Month(6,2007), 158.8);
	s2.add(new Month(7,2007), 148.3);

	TimeSeriesCollection dataset = new TimeSeriesCollection();
	dataset.addSeries(s1);
	dataset.addSeries(s2);
	
	JFreeChart chart = ChartFactory.createTimeSeriesChart(
	  "Time series graph", // title
	  "Month",             // x-axis label
	  "Values",            // y-axis label
	  dataset,             // data
	  true,                // create legend?
	  false,                    // generate tooltips?
	 false);                   // generate URLs?

	chart.setBackgroundPaint(Color.white);

	XYPlot plot = (XYPlot) chart.getPlot();
	plot.setBackgroundPaint(Color.white);
	plot.setDomainGridlinePaint(Color.lightGray);
	plot.setRangeGridlinePaint(Color.lightGray);
	plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
	plot.setDomainCrosshairVisible(true);
	plot.setRangeCrosshairVisible(true);

	XYItemRenderer r = plot.getRenderer();
	if (r instanceof XYLineAndShapeRenderer)
	{
	     XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
	     renderer.setBaseShapesVisible(true);
	     renderer.setBaseShapesFilled(true);
	}

	DateAxis axis = (DateAxis) plot.getDomainAxis();
	axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));

///////////////////////////////////////////Display the Chart on JSP/////////////////////////
	//Author: Kiran C Nair
	//e-mail: kirancnair@gmail.com

	ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());	// Here the info regarding the position and other coordinates of the chart are rendered
	BufferedImage bi = chart.createBufferedImage(700, 300, info); //A buffered image of the chart is created
	OutputStream output = response.getOutputStream();
	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);//An Encoder ic created to put the Buffered Image onto the screen as a JPEG

	encoder.encode(bi);//The image is displayed on the screen

	output.close();
///////////////////////////////////////////End Display the Chart on JSP/////////////////////////
	}
	catch (Exception e) {
		e.printStackTrace();
	}
%>
Just run this page and the chart will get loaded dynamically on the page. :twisted:[/size]
Last edited by kiranc_nair on Mon Apr 21, 2008 5:20 am, edited 1 time in total.

indio
Posts: 17
Joined: Thu Mar 27, 2008 4:14 pm

Post by indio » Fri Apr 04, 2008 12:46 pm

Hi all, this is a very insightful post.

I tried to read through most of the replies and I couldn't find somebody suggesting the idea I had.

If I understood correctly, you want to do this:

Code: Select all

start serving jsp
create graph
save graph to session/whatever
get the map data from it, serve it as text
open <img> tag
call the "special" imageServlet to read chart from session, serve it as png
close <img> tag
This algorithm though makes it impossible for somebody to get a simple graph out of your webapp. The url of the graph become depended on how the sessions are managed. Its tricky to get the graph as a png without asking for the complete jsp page.

Why not do the oposite? Instead of generating the image map in the local page and have the serveGraph page serve the graph by reading the session, why not have the serveGraph page actually make the graph and save the map to the session.

This way you can still get a simple png, but also get the map from the jsp.
  • - make a servet that creates e.g, the barchart you want:serveBarChart
    - serveBarChart makes the chart, saves to session the image map as a string, and writes the PNG output to the outstream.
    - In the jsp that you want to have the barchart appear, enter its location in a img tag, which is the serveBarChart servlet.
    - read the map from session
I hope I have understood the spirit of this post correctly and my solution makes sense!

indio
Posts: 17
Joined: Thu Mar 27, 2008 4:14 pm

Post by indio » Sun Apr 06, 2008 11:54 pm

Realized my previous suggestion couldn't work, there is no guarrantee that the imagemap can be saved in the session before the graph is served. In fact it never happens.

I 'll post another solution with a concrete implementation in a short while.

Locked