我有一个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);
}
您当前的(主)servlet应该仅用于html内容
为图表创建单独的servlet(可以在其中使用writeChartAsPNG
)
在JSP页面上,将其用作<img src="servChart?w1=100&w2=200">
和您的参数。
更新
您也可以在同一个servlet中进行图表计算。将JFreeChart
对象放入会话。在servChart?name=myChart
servlet中,从会话中获取JFreeChart(按属性名称)并以字节形式输出。