Reputation: 747
I have created web project in struts2.in that i have plotted a graph using jfreechart which i have implemented in my Action class.
http://www.java2s.com/Code/Java/Chart/JFreeChartTimeSeriesDemo10withperminutedata.htm
which displays the graph in separate applet kind of window i googled and find a way to save this chart as image so that in my jsp file i can include this image. But at the end when i was deploying i had to convert my project into a WAR file but if i convert project to a WAR i cant access images(graph) which gets changed based on users request.So i thought of save the chart/image in a buffer or some thing so that it gets displayed later deleted as soon new graph is requested or user logs out.
So can you ppl give some idea as to how to accomplish this. Thanks in Advance
Upvotes: 0
Views: 508
Reputation: 1261
I have written something similar to what you are trying to do. The way I accomplished this was to have a second servlet (very simple) that takes in parameters based on the requested chart and generates the chart as a PNG
. Basically, you call the servlet with the required parameters. You take those parameters and build your chart. The important part of returning the chart is happening in ChartUtilities.writeChartAsPNG(out, chart, 640, 480)
where the first parameter is the output stream for the response to the calling page. The second parameter is the chart you have built. The last two parameters are used for the size of the image. When you call this servlet it would be inside of
<img src="URL_to_Servlet" />
with the URL containing the needed parameters to build the chart.
Below is the code you will need, focusing solely on returning the chart as a dynamically built image from a Servlet
.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
public class ChartServlet extends HttpServlet {
/*
* (non-Javadoc) @see
* javax.servlet.http.HttpServlet#doGet(
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
JFreeChart chart = this.generateLineChart();
ServletOutputStream out = resp.getOutputStream();
resp.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, 640, 480);
out.close();
}
/**
* Generate chart.
*
* @return the j free chart
* @throws IOException Signals that an I/O exception has occurred.
*/
private JFreeChart generateLineChart() throws IOException {
return chart;
}
/*
* (non-Javadoc) @see javax.servlet.GenericServlet#init()
*/
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
System.out.println("Starting up charts servlet.");
}
}
Upvotes: 2