0

我有一个 servlet,它根据用户提交的表单数据执行一些计算。

我想在图表中绘制输入的输入值以及在同一网页上显示为文本的计算结果。

我可以使用 JFreeChart 创建图形,但如果我将它与 OutputStream 一起使用,它会覆盖表单页面。如果我存储图像并尝试在 JSP 中链接 URL,则不会显示图表。任何想法如何实现这一目标?

这是我的 servlet,它读取从浏览器提交的不同权重参数并使用 OutputStream 创建图表:

@WebServlet(name = "resultServlet", urlPatterns = {"/results"})
public class resultServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doPost(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try { 

     List<Double> weightsList = new ArrayList<Double>();
     int listpos = 0;

     DefaultPieDataset myServletPieChart = new DefaultPieDataset();

         double w1 = Double.valueOf(request.getParameter("w1"));
         myServletPieChart.setValue("WEIGHTONE", w1);
         weightsList.add(listpos, w1); 
         listpos++;
         double w2 = Double.valueOf(request.getParameter("w2"));
         myServletPieChart.setValue("WEIGHTTWO", w2);
         weightsList.add(listpos, w2); 
         listpos++;
         double w3 = Double.valueOf(request.getParameter("w3"));
         myServletPieChart.setValue("WEIGHTTHREE", w3);
         weightsList.add(listpos, w3); 
         listpos++;
         double w4 = Double.valueOf(request.getParameter("w4"));
         myServletPieChart.setValue("WEIGHTFOUR", w4);
         weightsList.add(listpos, w4); 

         request.setAttribute("WeightSel", weightsList);  //list of selected weights
         request.setAttribute("WeightSum", weightSum(weightsList)); //sum of selected weights
         request.setAttribute("CalcResult", resultCalculator(weightsList)); //result of some calculations performed on selected weights

         // set piechart attributes

         JFreeChart inputWeightsPie = ChartFactory.createPieChart("Selected Weights",myServletPieChart,true,true,false);
         response.setContentType("image/png"); /* Set the HTTP Response Type */

         OutputStream out = response.getOutputStream();
         ChartUtilities.writeChartAsPNG(out, inputWeightsPie, 400, 300);/* Write the data to the output stream */
         //or alternatively:
         // ImageIO.write(inputWeightsPie.createBufferedImage(400, 300), "png", out);
         out.close();

        }


    } catch (NumberFormatException nfe) {
        request.setAttribute("errorMessage", "value must be a number!"); 
    }
    ServletContext ctx = this.getServletContext();
    RequestDispatcher dispatcher = ctx.getRequestDispatcher("/index.jsp");
    dispatcher.forward(request, response);
}
4

1 回答 1

1

您当前的(主要)servlet 应仅用于 html 内容。
为图表创建单独的 servlet(您可以在其中使用writeChartAsPNG)。
在 JSP 页面上将其 <img src="servChart?w1=100&w2=200">与您的参数一起使用。

更新
您还可以在同一个 servlet 中进行图表计算。将JFreeChart对象放入会话。并在servChart?name=myChartservlet 中从会话中获取 JFreeChart(按属性名称)并作为字节输出。

于 2013-08-26T23:48:11.607 回答