user1016313
user1016313

Reputation: 1314

Displaying a jfreechart in a jsp page

I want to display a jfreechart chart in a jsp page. I have written code as follows -

...
<%
ChartCreator chart = new ChartCreator();
chart.createCategoryChart();
%>
<img src = "chart.jpg"/>

where the createCategoryChart() method creates the required jpg. It is stored in the eclipse folder(i have not put any path in my filename).

I am not able to view the chart in the jsp page, but the file is created.

What am I doing wrong?

Upvotes: 0

Views: 7151

Answers (1)

Hardik Mishra
Hardik Mishra

Reputation: 14877

I would suggest to use Servlet to create Chart.

JSP is mainly used for presentation (View).

Create a servlet which creates the chart and send back it as response.

import javax.imageio.ImageIO;


protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        OutputStream out = response.getOutputStream(); /* Get the output stream from the response object */
        response.setContentType("image/png"); /* Set the HTTP Response Type */
        ChartCreator chart = new ChartCreator(); // Create chart
        chart.createCategoryChart(); 
        ChartUtilities.writeChartAsPNG(out, chart, 400, 300);/* Write the data to the output stream */
    }

Call Servlet from JSP.

<img src="/drawChartServlet?type=myDesiredChart&width=..and other processed parameters" ..>

Upvotes: 5

Related Questions