我有一个 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);
}