ServletResponse 中getOUtStreatm 和getWriter 混合使用

ServletResponse 对象可以通过getOutStream()方法 获取页面输出流java.io.OutStream对象 out。

同时也可以通过getWriter()获取java.io.PrintWriter对象writer。

如果在一次操作中同时使用两个对象对外输出数据。可能会报异常。

java.lang.IllegalStateException: WRITER
  at org.eclipse.jetty.server.Response.getOutputStream(Response.java:681)

可以查看一下源码。

javax.servlet.ServletResponse接口中的定义如下: 
/**
     * Returns a {@link ServletOutputStream} suitable for writing binary 
     * data in the response. The servlet container does not encode the
     * binary data.  
     
     * <p> Calling flush() on the ServletOutputStream commits the response.
     
     * Either this method or {@link #getWriter} may 
     * be called to write the body, not both.
     *
     * @return				a {@link ServletOutputStream} for writing binary data	
     *
     * @exception IllegalStateException if the <code>getWriter</code> method
     * 					has been called on this response
     *
     * @exception IOException 		if an input or output exception occurred
     *
     * @see 				#getWriter
     *
     */

    public ServletOutputStream getOutputStream() throws IOException;

再看jetty的源码,jetty.server.Response的源码: 
public ServletOutputStream getOutputStream() throws IOException
    {
        if (_outputState!=NONE && _outputState!=STREAM)
            throw new IllegalStateException("WRITER");

        ServletOutputStream out = _connection.getOutputStream();
        _outputState=STREAM;
        return out;
    }


public PrintWriter getWriter() throws IOException
    {
        if (_outputState!=NONE && _outputState!=WRITER)
            throw new IllegalStateException("STREAM");

        /* if there is no writer yet */
        if (_writer==null)
        {
            /* get encoding from Content-Type header */
            String encoding = _characterEncoding;

            if (encoding==null)
            {
                /* implementation of educated defaults */
                if(_cachedMimeType != null)
                   encoding = MimeTypes.getCharsetFromContentType(_cachedMimeType);

                if (encoding==null)
                    encoding = StringUtil.__ISO_8859_1;

                setCharacterEncoding(encoding);
            }

            /* construct Writer using correct encoding */
            _writer = _connection.getPrintWriter(encoding);
        }
        _outputState=WRITER;
        return _writer;
    }
从源码的第3-4行可以得以验证,也就是说对于同一个response实例你只能使用其中的一个方法,不能两者混用。

备注一下。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值