using JFreeChart with JSP

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
quickjava
Posts: 1
Joined: Sat Apr 26, 2008 2:04 pm

Thanks

Post by quickjava » Sat Apr 26, 2008 2:09 pm

Thanks to all the above coders & especially the one who gave servlet code is very muck helpful.

Regards,
pani

aaa
Posts: 19
Joined: Thu Jul 03, 2008 3:12 pm

Need to generate dynamically with tooltip and url and show

Post by aaa » Thu Jul 03, 2008 4:25 pm

Dear All,

Using the following code,
I generated bar chart with category data set.
Stored the chart in a file and i pointed out the path in jsp to show
Its all working fine

But i dont want to store the image,
1. I want to generate it dynamically and show it in the jsp.
2. With URL
3. with tooltip with url
for these what i need to do?

And i am using ajax to show all these things in struts framework

code i have used is,

import mypackages;
......
.......
.......

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.awt.Color;

//JFree Chart stuff////////
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;

public class chartVC extends mypgm
{

public String rendering(HttpServletRequest request, HttpServletResponse response,String viewURL) throws Exception
{
try
{
constructChart(..., ..., request);
}
catch(Exception e)
{
e.printStackTrace();
}
return viewURL;
}

private void constructChart(..., ... HttpServletRequest request) throws Exception
{
DataSet dataSet = null;
Map timeValMap = new HashMap(10);
Reports finReports = new Reports();
gUtils gu = new gUtils();
try
{
Long[] timeValArr = DateUtil.getThisWeekTimeInterval();

Long fromDateStarted =timeValArr[0];
Long toDateStarted =timeValArr[1];
HashMap reportParametersMap = new HashMap(10);

String viewName = request.getParameter("viewName");

DefaultCategoryDataset pDataSet = new DefaultCategoryDataset();
DefaultCategoryDataset cDataSet = new DefaultCategoryDataset();

String week = "";
Long fromDate, toDate;
boolean dataAvailable = false;
String glType = "";
int increasesByCredit = 0;

for(int i=0; i< 4; i++)
{
fromDate = fromDateStarted - DateUtil.MILLISECONDS_IN_A_DAY*i*7;
toDate = toDateStarted - DateUtil.MILLISECONDS_IN_A_DAY*i*7;

reportParametersMap.put("fromDate",fromDate);
reportParametersMap.put("toDate",toDate);
reportParametersMap.put("cashbased",false);

HashMap reportDetailsMap = finReports.genReport(viewName,reportParametersMap);

switch (i)
{
case 0 : week="This Week";break;
case 1 : week="Previous Week";break;
case 2 : week = gu.getDateString(toDate);break;
case 3 : week = gu.getDateString(toDate);break;
}

if(viewName.equals("something"))
{
pDataSet.addValue((Number)reportDetailsMap.get("nI"), "amt",week);
pDataSet.addValue((Number)reportDetailsMap.get("nE"), "amt1",week);
}
}


//Chart Drawing stuff
JFreeChart chart =null;
if (viewName.equals("something"))
{
chart = createBarChart(pDataSet);
}

//Writing the chart in /themes/common/images/barchart.png
if (chart != null)
{
String fileSeparator = File.separator;
String serverHome = System.getProperty("server.home");
String fileName = serverHome+path+filename;

File file = new File(fileName);
ChartUtilities.saveChartAsPNG(file,chart,325,270);
}

}
finally
{
if ( dataSet != null )
{
dataSet.close();
}
}
}
/**
* @return a bar chart.
*/
private JFreeChart createBarChart(DefaultCategoryDataset dcDataSet) {

JFreeChart chart = ChartFactory.createBarChart(
null,
null,
null,
dcDataSet,
PlotOrientation.VERTICAL,
true,
true,
true
);

final CategoryAxis xAxis = new CategoryAxis("week");
final CategoryAxis yAxis = new CategoryAxis("Amt");

xAxis.setLowerMargin(0.0d); // percentage of space before first bar
xAxis.setUpperMargin(0.01d); // percentage of space after last bar
xAxis.setCategoryMargin(0.05d); // percentage of space between categories
yAxis.setCategoryMargin(0.0d); // percentage of space between categories

chart.setBackgroundPaint(Color.white);

CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.white);

final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());


BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(true);

renderer.setSeriesPaint(0, new Color(169,229,87));
renderer.setSeriesPaint(1, new Color(255,180,0));
renderer.setItemMargin(0.0d);

CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(
CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));

return chart;
}
}


and in jsp
<%
String chartImgLocation = fileNameWithPath; (hard coded the relative path)
%>
<td><img src="<%= chartImgLocation%>" valign="top" align="left" width="100%" height="270" /> </td>

and i am calling this jsp in another jsp using ajax.
Last edited by aaa on Sat Nov 20, 2010 4:23 pm, edited 1 time in total.

aaa
Posts: 19
Joined: Thu Jul 03, 2008 3:12 pm

any body know help me

Post by aaa » Mon Jul 07, 2008 8:06 am

any help?
Last edited by aaa on Sat Nov 20, 2010 4:24 pm, edited 1 time in total.

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

Generating multiple buffered PNG Images

Post by bztom33 » Tue Jan 06, 2009 11:50 pm

mjitch,

Did you ever find a solution to your problem?

aaa
Posts: 19
Joined: Thu Jul 03, 2008 3:12 pm

Post by aaa » Wed Jan 07, 2009 5:23 am

hi,
I have found solution to this

thanks for your reply
Last edited by aaa on Sat Nov 20, 2010 4:24 pm, edited 1 time in total.

Veronica06
Posts: 3
Joined: Fri Aug 13, 2010 8:14 pm
antibot: No, of course not.

Re: using JFreeChart with JSP

Post by Veronica06 » Fri Aug 13, 2010 8:17 pm

Hey Vaji

Can you send me the solution as i am also working on similar thing. I will get the idea how to proceed further. Thanks,

aaa
Posts: 19
Joined: Thu Jul 03, 2008 3:12 pm

Re: using JFreeChart with JSP

Post by aaa » Sat Nov 20, 2010 4:29 pm

hi,

use a servlet to construct and load the image on the fly, means when you load the page.

Example:
In jsp:
<img src="yourgraph.chart" />

include a servlet in your web.xml to filter out *.chart requests and generate the chart in the servlet and supply it to the jsp.

Regards
Vaji

mikato
Posts: 6
Joined: Thu Jan 13, 2011 6:11 pm
antibot: No, of course not.

Re: using JFreeChart with JSP

Post by mikato » Thu Jan 13, 2011 6:30 pm

I have been having trouble with the on-the-fly servlet method to have an image display in a JSP. Thanks for all the great help in this thread by the way.
Anyway, I have confirmed that communication is working with the servlet (web.xml and all that ok) since I had the servlet instead write some html into an iframe on the JSP and that worked fine. However when I try to make the chart image instead, it's blank and all it displays is the alt text for the img. Strange since I followed the examples fairly closely. I also tested having all the chart code within the servlet and just putting the servlet url into the address bar and same thing.

Here are my code snippets below.

In my JSP's Java code (I removed image map part for debugging):

Code: Select all

// TODO code application logic here
// create a dataset...
DefaultPieDataset data = new DefaultPieDataset();//d
data.setValue("Category 1", 43.2);
data.setValue("Category 2", 27.9);
data.setValue("Category 3", 79.5);
// create a chart...
JFreeChart chart = ChartFactory.createPieChart(
"Sample Pie Chart",
data,
true, // legend?
true, // tooltips?
false // URLs?
);

session.setAttribute("chart", chart);
In my JSP's HTML part:

Code: Select all

<img src="ChartViewerServlet"  alt="THIS SHOULD BE THE CHART HERE">
In my ChartViewerServlet.java:

Code: Select all

            // get the chart from storage in session var (set there by caller)
            HttpSession session = request.getSession();
            JFreeChart chart = (JFreeChart) session.getAttribute("chart");
            // set the content type so the browser can see this as it is
            response.setContentType( "image/png" );

            // generate and send the png
            BufferedImage buf = chart.createBufferedImage(640, 400, null);
            PngEncoder encoder = new PngEncoder( buf, false, 0, 9 );
            response.getOutputStream().write( encoder.pngEncode() );
This seems straightforward to me. Any ideas where I'm going wrong? Am I missing something? I also tried setting the BufferedImage in the JSP first and then using that in the servlet instead but same result. Thanks for any help!

mikato
Posts: 6
Joined: Thu Jan 13, 2011 6:11 pm
antibot: No, of course not.

Re: using JFreeChart with JSP

Post by mikato » Thu Jan 13, 2011 11:07 pm

Ah I figured something out. Using this article as an example I switched my

Code: Select all

            // send the picture
            BufferedImage buf = chart.createBufferedImage(640, 400, null);
            PngEncoder encoder = new PngEncoder( buf, false, 0, 9 );
            response.getOutputStream().write( encoder.pngEncode() );
to just

Code: Select all

            //send the picture
            ChartUtilities.writeChartAsPNG(out, chart, 640, 400);
and the chart image showed! I still do not know why the other method for writing the data didn't work.

stelal
Posts: 1
Joined: Wed Mar 22, 2017 10:44 am
antibot: No, of course not.

Re: using JFreeChart with JSP

Post by stelal » Wed Mar 22, 2017 10:51 am

Is there a way to change the background color because the current background color is pink?

John Matthews
Posts: 513
Joined: Wed Sep 12, 2007 3:18 pm

Re: using JFreeChart with JSP

Post by John Matthews » Wed Mar 22, 2017 7:21 pm

It might be the alpha channel problem discussed here.

Locked