有一个使用SerlvetResponse输出图像的例子,代码如下:
<%
BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.fillRect(0,0,400,400);
g.setColor(new Color(255,0,0));
g.fillArc(20,20,100,100,30,120);
g.setColor(new Color(0,255,0));
g.fillArc(20,20,100,100,150,20);
g.setColor(new Color(0,0,255));
g.fillArc(20,20,100,100,270,120);
g.setColor(new Color(0,0,0));
g.drawString("red:climb" , 300, 80);
g.drawString("green:swim", 300, 120);
g.drawString("blue:jump", 300, 160);
ImageIO.write(image, "bmp", response.getOutputStream());
//out.clear();
//out = pageContext.pushBody();
%>
在Tomcat下运行时抛出如下异常:
at org.apache.catalina.connector.Response.getWriter(Response.java:601)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:196)
..................
at org.apache.jsp.pages.drawImage_jsp._jspService(drawImage_jsp.java:84)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98).
...............
查看转换后的JSP代码,发现第84行如下(绿色高亮处):
finally
{
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
}
我们看到在JSP页面释放资源的时候,调用了ServetResponse.getWriter()方法,之后程序即抛出异常了,查看Servlet的API发现问题:
public java.io.PrintWriter getWriter() throws java.io.IOException
- Returns a
PrintWriterobject that can send character text to the client. ThePrintWriteruses the character encoding returned bygetCharacterEncoding(). If the response's character encoding has not been specified as described ingetCharacterEncoding(i.e., the method just returns the default valueISO-8859-1),getWriterupdates it toISO-8859-1.Calling flush() on the
PrintWritercommits the response.Either this method or
getOutputStream()may be called to write the body, not both. - Returns:
- a
PrintWriterobject that can return character data to the client Throws: UnsupportedEncodingException- if the character encoding returned bygetCharacterEncodingcannot be usedjava.lang.IllegalStateException- if thegetOutputStreammethod has already been called for this response objectjava.io.IOException- if an input or output exception occurred See Also: getOutputStream(),setCharacterEncoding(java.lang.String)
- a
如API所言,由于ServletResponse.getOutputStream()方法和该方法都有可能被调用,来输出JSP页面的内容,如果其中的一个方法被调用了,再调用另一个方法就会抛出异常。
解决方法如下:
将JSP页面的最后两行代码的注释去掉,这两行代码的作用如下:
out.clear():清空缓存的内容。
pageContext.pushBody():参考API
public BodyContent pushBody()
- Return a new BodyContent object, save the current "out" JspWriter, and update the value of the "out" attribute in the page scope attribute namespace of the PageContext.
- Returns:
- the new BodyContent
·返回一个新的BodyContent(代表一个HTML页面的BODY部分内容)
·保存JspWriter实例的对象out
·更新PageContext的out属性的内容
本文介绍了一个使用Servlet输出图像的示例,并详细分析了在Tomcat环境下运行时出现的异常原因。通过调整JSP页面代码,解决了ServletResponse.getWriter()与getOutputStream()冲突的问题。
1996

被折叠的 条评论
为什么被折叠?



