关于Servlet中getWriter()和getOutputStream()方法的疑惑

由于现在是刚刚接触Servlet技术,今天在看韩老师的关于servlet技术的视频中讲到getWriter()和getOutputStream()方法再同一个Response对象中不能同时调用。

当时,听了就觉得有些奇怪,为什么不允许呢?

带着疑问,我还是好奇的敲了以下测试代码:

response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		OutputStream out = response.getOutputStream();
		
		out.write("helloworld".getBytes());
		out.flush();
		out.close();
		PrintWriter writer = response.getWriter();
		writer.println("你是谁呢");
		writer.close();

结果果不其然的发生了如下错误:

java.lang.IllegalStateException: getOutputStream() has already been called for this response

这下我不服气,为什么他就不能同时在一个Response对象中同时访问呢?而且,我也已经在我要获得字符流的时候,已经将字节流out 给关闭了。

经过几番尝试后,我还是无果,因为自己能力有限,对于Servlet技术知之甚少,所以,我去查看 Servlet API: 在 API中 这样写道:

getOutputStream

ServletOutputStream getOutputStream()
                                    throws java.io.IOException
Returns a ServletOutputStream suitable 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:
a ServletOutputStream for writing binary data
Throws:
java.lang.IllegalStateException - if the getWriter method has been called on this response
java.io.IOException - if an input or output exception occurred
See Also:
getWriter()

好吧,原来文档里直接说出 getWriter()和 getOutputStream() 不可以同时用来提交这个response;但是这句话还是让我这个初学者不能解惑,

为什么啊?servlet技术为什么要做出这样的规范?

带着疑问,我只能是上GOOGLE了,在敲入关键字后,发现同样是有许多这样的问题存在;当我满心欢喜的打开他们的回答时,却让我很是失望,因为几乎都是和我一样,将API中的这样一句话


Either this method or getWriter() may be called to write the body, not both

不过,他们倒是说。如果要使用Writer可以通过使用包装流去包装outputStream。但是这个不是重点。


所以,综上所述,我的能力已不足以帮助我了解该规范的原因,所以,还希望大牛们能够给点指点


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值