ServletResponse的getOutputStream()与getWriter()使用冲突

ServletResponse的getOutputStream()与getWriter()在使用上的冲突问题:

在Servlet和Filter中使用ServletResponse的getOutputStream()与getWriter()方法时,抛出异常如下:

java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:638)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:214)

JavaEE API中ServletResponse类关于这两个方法的描述如下:

ServletOutputStream getOutputStream() throws java.io.IOException
Returns aServletOutputStreamsuitable for writing binary data in the response. The servlet container does not encode the binary data.

Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, not both.

Returns: aServletOutputStreamfor writing binary data

Throws: IllegalStateException- if the getWriter method has been called on this response java.io.IOException- if an input or output exception occurred

java.io.PrintWriter getWriter()throws java.io.IOException
Returns a PrintWriterobject that can send character text to the client. The PrintWriteruses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described ingetCharacterEncoding(i.e., the method just returns the default valueISO-8859-1),getWriter updates it toISO-8859-1.

Calling flush() on thePrintWritercommits the response.Either this method or getOutputStream() may be called to write the body, not both.

Returns: a PrintWriter object that can return character data to the client

Throws: UnsupportedEncodingException- if the character encoding returned by getCharacterEncoding cannot be used IllegalStateException- if the getOutputStream method has already been called for this response object java.io.IOException- if an input or output exception occurred

原因就是这两个方法都有可能向同一个response body里写入数据,但这两个方法不能同时使用

解决方法就是在Servlet和Filter两边约定: 

使用java.io.PrintWriter或者javax.servlet.ServletOutputStream之一;

最后别忘记在这两个类对象上调用flush() 和close()方法!


你可能感兴趣的:(ServletResponse的getOutputStream()与getWriter()使用冲突)