using JFreeChart with JSP
Need to generate dynamically with tooltip and url and show
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.
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.
any body know help me
any help?
Last edited by aaa on Sat Nov 20, 2010 4:24 pm, edited 1 time in total.
Generating multiple buffered PNG Images
mjitch,
Did you ever find a solution to your problem?
Did you ever find a solution to your problem?
-
- Posts: 3
- Joined: Fri Aug 13, 2010 8:14 pm
- antibot: No, of course not.
Re: using JFreeChart with JSP
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,
Can you send me the solution as i am also working on similar thing. I will get the idea how to proceed further. Thanks,
Re: using JFreeChart with JSP
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
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
Re: using JFreeChart with JSP
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):
In my JSP's HTML part:
In my ChartViewerServlet.java:
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!
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);
Code: Select all
<img src="ChartViewerServlet" alt="THIS SHOULD BE THE CHART HERE">
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() );
Re: using JFreeChart with JSP
Ah I figured something out. Using this article as an example I switched my
to just
and the chart image showed! I still do not know why the other method for writing the data didn't work.
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() );
Code: Select all
//send the picture
ChartUtilities.writeChartAsPNG(out, chart, 640, 400);
Re: using JFreeChart with JSP
Is there a way to change the background color because the current background color is pink?
-
- Posts: 513
- Joined: Wed Sep 12, 2007 3:18 pm
Re: using JFreeChart with JSP
It might be the alpha channel problem discussed here.