使用JFreeChart向页面输出图时,response.getOutputStream()报错
一.错误:
使用JFreeChart向页面输出图时,使用response.getOutputStream()会有这样的异常错误提示信息:java.lang.IllegalStateException: getOutputStream() has already been called for this response;
struts Action中的代码如下:
- package com.fck.struts.action;
- import java.io.File;
- import java.io.IOException;
- import java.io.OutputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
- import org.apache.struts.actions.DispatchAction;
- import org.jfree.chart.ChartUtilities;
- import org.jfree.chart.JFreeChart;
- import service.GradeService;
- import com.fck.struts.form.ChartForm;
- public class ChartAction extends DispatchAction {
- //注入
- GradeService chartService;
- public void setChartService(GradeService chartService) {
- this.chartService = chartService;
- }
- public ActionForward showChart(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response) {
- ChartForm chartForm = (ChartForm) form;
- JFreeChart chart = chartService.getChart();
- try {
- ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 600, 400);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return mapping.findForward("succ");
- }
- }
二.原因:
代码中的第34行,调用了response.getOutputStream(),与JSP页面的out对象(注:out对象为response.getWriter类在JSP中的内置对象)产生了冲突。
为什么会产生冲突图呢?这个是因为Servlet规范说明,不能既调用response.getOutputStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出IllegalStateException。
三.解决办法
在目标页面加上2行代码,就OK了。
只需要在jsp页面的最后加上两条语句: out.clear();out=pageContext.pushBody();即可(其中out,pageContext均为jsp内置对象!)
- <body>
- <%
- out.clear();
- out=pageContext.pushBody();
- %>
- </body>