using JFreeChart with JSP

A free public discussion forum for the JFreeChart class library.

using JFreeChart with JSP

Postby pmarsollier » Wed Jul 21, 2004 8:15 am

The way to use JSP with JFreeChart.

The point is that you need 2 HTTP requests to get the picture AND the imagemap because of the way a browser parses HTML.
1 for the html => from the JSP
1 for the picture => from servlet

The picture has to be send by a servlet because a JSP CANNOT send anything else than text.

So, in your JSP you :
- produce the graph, and store it in the session or in a singleton in your server or anywhere you want, in as much as you can get it in anthoer context.
- produce the image map from that graph
- call the image from the servlet

in your servlet you :
- get the graph from the session or whereever it is stored and send it.

I really prefer store the JFreeChart instance rather than a BufferedImage, because with it, you can generate what you want when you need it :
- you can send the size as parameter to your servelt and generate a picture the size you need
- you can generated PNG, JPG, PDF, etc ... from it


JSP :

Code: Select all
--  in the java code part :
// produce chart ....

// store it the way you want : here in session
<%@ page session="true" %>
session.setAttribute( "chart", chart );

// get ImageMap
ChartRenderingInfo info = new ChartRenderingInfo();
// populate the info
chart.createBufferedImage(640, 400, info);
String imageMap = ChartUtilities.getImageMap( "map", info );


-- in the HTML part
// include the map
<%= imageMap%>

// include the call for the image
<IMG src="chartviewer" usemap="#map">


ChartViewer Servlet :

Code: Select all
public class ChartViewer extends HttpServlet
{
   public void doGet( HttpServletRequest request, HttpServletResponse response )
      throws ServletException, IOException
   {
      // get the chart from storage
      JFreeChart  chart = (JFreeChart) session.getAttribute( "chart" );
      // set the content type so the browser can see this as it is
      response.setContentType( "image/png" );
   
      // send the picture
      BufferedImage buf = chart.createBufferedImage(640, 400, null);
      PngEncoder encoder = new PngEncoder( buf, false, 0, 9 );
      response.getOutputStream().write( encoder.pngEncode() );
   }
}


It's the same for JPG :
Code: Select all
public class ChartViewer extends HttpServlet
{
   public void doGet( HttpServletRequest request, HttpServletResponse response )
      throws ServletException, IOException
   {
      // get the chart from storage
      JFreeChart  chart = (JFreeChart) session.getAttribute( "chart" );
      // set the content type so the browser can see this as it is
      response.setContentType( "image/jpeg" );
   
      // send the picture
      BufferedImage buf = chart.createBufferedImage(640, 400, null);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder( response.getOutputStream() );
      JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam( buf );
      param.setQuality( 0.75f, true );
      encoder.encode( buf, param );
   }
}



for PDF, it a bit different :

Code: Select all
public void doGet( HttpServletRequest request, HttpServletResponse response )
   throws ServletException, IOException
{
   // get the chart from storage
   JFreeChart  chart = (JFreeChart) session.getAttribute( "chart" );
   // set the content type so the browser can see this as it is
   response.setContentType( "application/pdf" );
   
   int width = 640;
   int height = 480;
   Rectangle pagesize = new Rectangle( width, height );
   Document document = new Document( pagesize, 50, 50, 50, 50 );
   OutputStream os = new BufferedOutputStream( out );
   PdfWriter writer = PdfWriter.getInstance( document, out );
   //      document.addAuthor("JFreeChart");
   //      document.addSubject("Demonstration");
   document.open();
   PdfContentByte cb = writer.getDirectContent();
   PdfTemplate tp = cb.createTemplate( width, height );
   Graphics2D g2 = tp.createGraphics( width, height, new DefaultFontMapper() );
   Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height );
   chart.draw(g2, r2D);
   g2.dispose();
   cb.addTemplate(tp, 0, 0);
   document.close();
}
Last edited by pmarsollier on Thu Jul 22, 2004 6:18 am, edited 4 times in total.
pmarsollier
 
Posts: 49
Joined: Thu Jul 08, 2004 8:54 am
Location: France

Postby terrie » Wed Jul 21, 2004 8:26 am

THANKS A LOT

Where should I put the following code?where should I place after complie the following class?Wht the name of the class should be?

chartviewer Servlet :

private void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
// get the chart from storage
JFreeChart chart = (JFreeChart) session.getAttribute( "chart" );
// set the content type so the browser can see this as it is
response.setContentType( "image/png" );
// you might use response.setContentType( "application/pdf" ) for PDF

// send the picture
BufferedImage buf = chart.createBufferedImage(640, 400, info);
PngEncoder encoder = new PngEncoder( buf, false, 0, 9 );
response.getOutputStream().write( encoder.pngEncode() );
}
terrie
 
Posts: 11
Joined: Wed Jul 21, 2004 4:09 am

Postby terrie » Wed Jul 21, 2004 9:04 am

thanks in advance

another question is that how to modify the xml to use the servlet class?

THX
terrie
 
Posts: 11
Joined: Wed Jul 21, 2004 4:09 am

Postby pmarsollier » Wed Jul 21, 2004 9:09 am

Well, just one thing to do : RTFM !

it depends of your Application Server.

at least, you need this :

<web-app>
<servlet>
<servlet-name>ChartViewer</servlet-name>
<servlet-class>ChartViewer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ChartViewer</servlet-name>
<url-pattern>/chartviewer</url-pattern>
</servlet-mapping>
</web-app>
pmarsollier
 
Posts: 49
Joined: Thu Jul 08, 2004 8:54 am
Location: France

Postby terrie » Wed Jul 21, 2004 9:12 am

one strange question u hve reply for my post this one:
after a few minute, i refresh the browser and the ur reply post can't be found now....

>>
THANKS A LOT

Where should I put the following code?where should I place after complie the following class?Wht the name of the class should be?

chartviewer Servlet :

private void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
// get the chart from storage
JFreeChart chart = (JFreeChart) session.getAttribute( "chart" );
// set the content type so the browser can see this as it is
response.setContentType( "image/png" );
// you might use response.setContentType( "application/pdf" ) for PDF
:
.
<<
terrie
 
Posts: 11
Joined: Wed Jul 21, 2004 4:09 am

Postby terrie » Thu Jul 22, 2004 4:16 am

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.data.*;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.renderer.BarRenderer;
import org.jfree.chart.renderer.StandardXYItemRenderer;
import org.jfree.chart.renderer.StackedXYAreaRenderer;
import org.jfree.chart.renderer.XYAreaRenderer;
import org.jfree.chart.plot.*;
import org.jfree.chart.entity.*;
import org.jfree.chart.labels.*;
import org.jfree.chart.urls.*;
import org.jfree.chart.servlet.*;
.
.
.

--------------------Configuration: JDK version <Default>--------------------
C:\tomcat\webapps\PSA\WEB-INF\classes\ChartViewer.java:32: cannot resolve symbol
symbol : variable session
location: class ChartViewer
JFreeChart chart = (JFreeChart) session.getAttribute( "chart" );
^
C:\tomcat\webapps\PSA\WEB-INF\classes\ChartViewer.java:37: cannot resolve symbol
symbol : class BufferedImage
location: class ChartViewer
BufferedImage buf = chart.createBufferedImage(640, 400, info);
^
C:\tomcat\webapps\PSA\WEB-INF\classes\ChartViewer.java:37: cannot resolve symbol
symbol : variable info
location: class ChartViewer
BufferedImage buf = chart.createBufferedImage(640, 400, info);
^
C:\tomcat\webapps\PSA\WEB-INF\classes\ChartViewer.java:38: cannot resolve symbol
symbol : class PngEncoder
location: class ChartViewer
PngEncoder encoder = new PngEncoder( buf, false, 0, 9 );
^
C:\tomcat\webapps\PSA\WEB-INF\classes\ChartViewer.java:38: cannot resolve symbol
symbol : class PngEncoder
location: class ChartViewer
PngEncoder encoder = new PngEncoder( buf, false, 0, 9 );
^
5 errors

Process completed.


thank you very much !
terrie
 
Posts: 11
Joined: Wed Jul 21, 2004 4:09 am

Postby terrie » Thu Jul 22, 2004 4:44 am

By adding
<<
import com.keypoint.PngEncoder;
import java.awt.image.*;
>>
remain two errors

--------------------Configuration: JDK version <Default>--------------------
C:\tomcat\webapps\PSA\WEB-INF\classes\ChartViewer.java:40: cannot resolve symbol
symbol : variable session
location: class ChartViewer
JFreeChart chart = (JFreeChart) session.getAttribute( "chart" );
^
C:\tomcat\webapps\PSA\WEB-INF\classes\ChartViewer.java:45: cannot resolve symbol
symbol : variable info
location: class ChartViewer
BufferedImage buf = chart.createBufferedImage(640, 400, info);
^
2 errors

Process completed.
terrie
 
Posts: 11
Joined: Wed Jul 21, 2004 4:09 am

Postby pmarsollier » Thu Jul 22, 2004 6:23 am

Well, I should have noticed that my aim is not to teach you java, but it's to explain the way to use JSP and JFreeChart together. I put a little code, extracted from mine, but not recompiled alone.

from a JSP, there is a way to get session by declaring it
<% @page session="true" %>
and BufferedImage is in the package java.awt.image
pmarsollier
 
Posts: 49
Joined: Thu Jul 08, 2004 8:54 am
Location: France

Postby psupa » Mon Jul 26, 2004 4:11 am

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());
   
  }

  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
    doGet(request, response);
  }

  //Process the HTTP Put request
  public void doPut(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
  }

  //Clean up resources
  public void destroy() {
  }

}


2. Compile and store the servlet under WEB-INF/classes
<appname>WEB-INF/classes/myapp/webwork/servlets
3. Create a servlet map in web.xml

Code: Select all
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
  <servlet>
    <servlet-name>ChartViewer</servlet-name>
    <servlet-class>myapp.webwork.servlets.ChartViewer</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ChartViewer</servlet-name>
    <url-pattern>/servlet/ChartViewer</url-pattern>
  </servlet-mapping>
</web-app>


4. Create a chart in a java bean (Pie3DDemo.java)

Code: Select all
/**
*
* JFreeChart version 0.9.20
* Called by Pie3DDemo.jsp
*
*/

package myapp.webwork.beans;

import java.io.*;
import java.awt.*;
import java.util.*;
import java.awt.image.*;
import org.jfree.data.*;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.urls.*;
import org.jfree.chart.entity.*;
import javax.servlet.http.*;

public class Pie3DDemo {

  public Pie3DDemo() {
  }

  private DefaultPieDataset getDataset() {
    // categories...
    String[] section = new String[] {
      "Jan","Feb","Mar","Apr","May","Jun",
      "Jul","Aug","Sep","Oct","Nov","Dec"
   };

    // data...
    double[] data = new double[section.length];
    for (int i = 0; i < data.length; i++) {
        data[i] = 10 + (Math.random() * 10);
    }

    // create the dataset...
    DefaultPieDataset dataset = new DefaultPieDataset();
    for (int i = 0; i < data.length; i++) {
        dataset.setValue(section[i], data[i]);
    }
    return dataset;
  }

  public String getChartViewer(HttpServletRequest request, HttpServletResponse response) {
    DefaultPieDataset dataset = getDataset();
    // create the chart...
    JFreeChart chart = ChartFactory.createPie3DChart(
          "Pie3D Chart Demo",  // chart title
          dataset,             // data
          true,                // include legend
          true,
          false
    );

    // set the background color for the chart...
    chart.setBackgroundPaint(Color.cyan);
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setNoDataMessage("No data available");
     
    // set drilldown capability...
    plot.setURLGenerator(new StandardPieURLGenerator("Bar3DDemo.jsp","section"));
    plot.setLabelGenerator(null);

    // OPTIONAL CUSTOMISATION COMPLETED.

    ChartRenderingInfo info = null;
    HttpSession session = request.getSession();
    try {

      //Create RenderingInfo object
      response.setContentType("text/html");
      info = new ChartRenderingInfo(new StandardEntityCollection());
      BufferedImage chartImage = chart.createBufferedImage(640, 400, info);

      // putting chart as BufferedImage in session, 
      // thus making it available for the image reading action Action.
      session.setAttribute("chartImage", chartImage);

      PrintWriter writer = new PrintWriter(response.getWriter());
      ChartUtilities.writeImageMap(writer, "imageMap", info);
      writer.flush();
    
    }
    catch (Exception e) {
       // handel your exception here
    }
   
    String pathInfo = "http://";
    pathInfo += request.getServerName();
    int port = request.getServerPort();
    pathInfo += ":"+String.valueOf(port);
    pathInfo += request.getContextPath();
    String chartViewer = pathInfo + "/servlet/ChartViewer";
    return chartViewer;
  }
}


5. Compile and store the bean under WEB-INF/classes
<appname>WEB-INF/classes/myapp/webwork/beans
6. Create Pie3DDemo.jsp code

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>

<%String chartViewer = myChart.getChartViewer(request, response);%>

<img src="<%=chartViewer%>" border=0 usemap="#imageMap">

</body>
</html>
psupa
 
Posts: 13
Joined: Fri Jun 18, 2004 9:32 am

Cant display chart through JSP

Postby AA » Sat Aug 14, 2004 8:44 am

Hi, I am using struts for chart generation.
My Struts code is as below :
=============================
Public ActionForward createXyChart(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)
throws Exception
{
JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
System.out.println("Action class " + chart );

response.reset();
// we are sending the html <MAP> tag, so we need to set the proper content-type
response.setContentType("text/html");

ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
ServletOutputStream sos = response.getOutputStream();
HttpSession session = request.getSession();

try {
BufferedImage chartImage = chart.createBufferedImage(640, 400, info);
System.out.println("Action class BufferedImage " + chartImage );
// putting chart as BufferedImage in session,
// thus making it available for the image reading action Action.
session.setAttribute("chartImage", chartImage);

filename = ServletUtilities.saveChartAsPNG(chart, 500, 300, info, session);
PrintWriter writer = new PrintWriter(sos);
session.setAttribute("File", filename);
ChartUtilities.writeImageMap(writer, filename, info);
System.out.println("Action class writeImageMap created");
writer.flush();


}
catch(Exception e) {
e.printStackTrace();
// managing exception here
}
String forward = "xyChart";
return mapping.findForward(forward);}


==============================

My JSP file is


%
String fileName = (String)session.getAttribute("File");
System.out.println("In JSP >>>>>>>> CHART ");
String graphURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + fileName;
String reportName =(String) request.getParameter("reportName");
BufferedImage chartImage =(BufferedImage) session.getAttribute("chartImage");
System.out.println("In JSP >>>>>>>> fileName " + fileName);
System.out.println("In JSP >>>>>>>> graphURL " + graphURL);
System.out.println("In JSP >>>>>>>> ContPath " + request.getContextPath());




%>

<img src="<%= graphURL %>" width=400 height=300 border=0 usemap="#<%= fileName %>">

================================

I gets blank screen with view source

<MAP NAME="jfreechart-19494.png">
<AREA SHAPE="RECT" COORDS="60,114,64,118" title="DEAL: (0, 2,772)" href="index.html?series=0&item=0">
<AREA SHAPE="RECT" COORDS="118,42,122,46" title="DEAL: (1, 4,444)" href="index.html?series=0&item=1">
<AREA SHAPE="RECT" COORDS="177,42,181,46" title="DEAL: (2, 4,444)" href="index.html?series=0&item=2">
<AREA SHAPE="RECT" COORDS="352,42,356,46" title="DEAL: (5, 4,444)" href="index.html?series=0&item=3">
<AREA SHAPE="RECT" COORDS="469,42,473,46" title="DEAL: (7, 4,444)" href="index.html?series=0&item=4">
</MAP>

Can anybody will help me?
I saw all the faqs related this but could not solve.
I can display chart with ChartUtilities.writeChartAsJPEG(sos,chart,500,300); but i dont want that. I want to show thro jsp..

Thanks
AA
 

Postby Guest » Mon Aug 16, 2004 3:35 am

This thread is to process the image via stream buffer, not store image in filesystem. If you would like to store the image in the filesystem, you need to see this thread http://www.jfree.org/phpBB2/viewtopic.php?t=5513 posted by Richard. There is a link to download an example war file.
Guest
 

Cannot find org/jfree/base/Library

Postby Marvin » Fri Aug 20, 2004 9:54 am

When a execute the example jsp in this post i get the following error. What am i doing wrong?

exception

javax.servlet.ServletException: org/jfree/base/Library
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:867)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:800)
org.apache.jsp.Pie3DDemo_jsp_jsp._jspService(Pie3DDemo_jsp_jsp.java:81)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:133)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:311)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:305)


root cause

java.lang.NoClassDefFoundError: org/jfree/base/Library
org.jfree.chart.JFreeChart.<clinit>(JFreeChart.java:187)
org.jfree.chart.ChartFactory.createPieChart3D(ChartFactory.java:424)
org.jfree.chart.ChartFactory.createPie3DChart(ChartFactory.java:1799)
abakus.Pie3DDemo.getChartViewer(Pie3DDemo.java:50)
org.apache.jsp.Pie3DDemo_jsp_jsp._jspService(Pie3DDemo_jsp_jsp.java:67)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:133)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:311)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:305)
Marvin
 

Postby Guest » Tue Aug 24, 2004 2:57 am

Code: Select all
java.lang.NoClassDefFoundError: org/jfree/base/Library


Make sure you put jcommon library under WEB-INF/lib
Guest
 

org.jfree.base.Library class not found

Postby Guest » Tue Aug 24, 2004 3:10 pm

> Make sure you put jcommon library under WEB-INF/lib

Sorry, but this class (or even the org.jfree.base package) does not exist in either the jfreechart 0.9.20 or the jcommon 0.9.4 libraries.
Guest
 

Postby Steve » Tue Aug 24, 2004 5:56 pm

org.jfree.base.Library exists in jcommon-0.9.5
Steve
 
Posts: 53
Joined: Mon Dec 22, 2003 8:29 pm

Next

Return to JFreeChart - General

Who is online

Users browsing this forum: Yahoo [Bot] and 17 guests