从servlet返回动态生成的饼图并在JSP中显示

时间:2013-12-12 01:57:55

标签: jsp servlets jfreechart pie-chart dynamically-generated

需要你的帮助!

我找到了这个网站> http://www.avajava.com/tutorials/lessons/how-do-i-return-a-dynamically-generated-pie-chart-from-a-servlet.html

此网站显示如何生成饼图并在servlet中显示。我设法在servlet中显示。但是我希望在JSP中显示。我试着寻找答案。有人说在JSP中,将img源映射到servlet。我尝试过,但我没有成功。

以下是我的代码如果有人帮我在jsp上显示图表会很棒。我是jsp / servlet的新手。谢谢!

chart.jsp

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

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;
}

编辑:

Servlet在web.xml中的映射是:

<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>

1 个答案:

答案 0 :(得分:1)

您可以通过使用http://localhost:8080/yourcontext/piechart网址打开浏览器来测试该图表,如果一切正常,请使用src标记img属性的relative-url或absolute-url。

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

或者

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