1

Need your help!

I found this website > http://www.avajava.com/tutorials/lessons/how-do-i-return-a-dynamically-generated-pie-chart-from-a-servlet.html

This website show how to generate a pie chart and display in servlet. I managed to display in servlet. However I want to display in JSP instead. I tried looking for the answer. Some said that in JSP, map the img sources to the servlet. I tried but I did not managed to do it.

Below are my codes It would be great if someone help me to display the chart at jsp. I am new to jsp/servlet. Thanks!

at chart.jsp

<img border="0" src="ChartExample/src/servlet/ChartServlet.java"
    width="100" height="100">

at ChartServlet.java

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("image/png");

    OutputStream outputStream = response.getOutputStream();

    JFreeChart chart = getChart();
    int width = 500;
    int height = 350;
    ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
}

public JFreeChart getChart() {
    DefaultPieDataset dataset = new DefaultPieDataset();


    Statement stmt = null;
    Connection currentCon = null;


    ChartDao ChartDao = new ChartDao ();
    int chickenrice = ChartDao.CheckChickenRiceRow();
    int currychicken = ChartDao.CheckCurryRiceRow();

    dataset.setValue("Chicken Rice", chickenrice);
    dataset.setValue("Curry Chicken", currychicken);

    boolean legend = true;
    boolean tooltips = false;
    boolean urls = false;

    JFreeChart chart = ChartFactory.createPieChart("Orders", dataset, legend, tooltips, urls);

    chart.setBorderPaint(Color.GREEN);
    chart.setBorderStroke(new BasicStroke(5.0f));
    chart.setBorderVisible(true);

    return chart;
}

EDIT:

Servlet is mapped in web.xml is:

<servlet> 
   <servlet-name>ChartServlet</servlet-name>
   <servlet-class>servlet.ChartServlet</servlet-class>
 </servlet> 
 <servlet-mapping>
    <servlet-name>ChartServlet</servlet-name>
     <url-pattern>/piechart</url-pattern>
  </servlet-mapping>
3
  • You need to specify servlet-url at src attribute instead of location of Java source file. Dec 12, 2013 at 2:00
  • @AVD so is it like this? <img border="0" src="/piechart" width="100" height="100">
    – Purple Owl
    Dec 12, 2013 at 2:04
  • That's true. <img src='/piechart alt=''/>` Dec 12, 2013 at 2:58

1 Answer 1

1

You can test that chart by opening browser with http://localhost:8080/yourcontext/piechart url and if everything is OK then use relative-url or absolute-url with src attribute of img tag.

<img src='/piechart' alt='Pie chart'/>

Or

<img src='http://localhost:8080/yourcontext/piechart' alt='Pie chart'/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.