如何在同一个servlet请求中使用getOutputStream()和getWriter()? [英] How do I use getOutputStream() and getWriter() in the same servlet request?

查看:632
本文介绍了如何在同一个servlet请求中使用getOutputStream()和getWriter()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在同一个servlet请求中使用getOutputStream()和getWriter()?

How do I use getOutputStream() and getWriter() in the same servlet request?

推荐答案

你不能使用他们两个在同一时间。如果您第一次执行 getOutputStream(),则不能在同一请求中执行 getWriter(),反之亦然。但是,您可以将 ServletOuptputStream 包装在 PrintWriter 中,以获得与<$ c $相同类型的编写器。 c> getWriter()。

You can't use them both at the same time. If you first did getOutputStream() you can't consequently in the same request do getWriter() and vice versa. You can however wrap your ServletOuptputStream in a PrintWriter to get the same kind of writer you would have from getWriter().

ServletOutputStream out = response.getOutputStream();
// Notice encoding here, very important that it matches that of
// response.setCharacterEncoding();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "utf-8"));

另一种不使用 getWriter()的解决方案是使用 PrintStream 这有点类似,但是你没有 Writer 或<$的类型兼容性c $ c> PrintWriter 。

Another solution to not using getWriter() is to use a PrintStream which is somewhat similar, but then you don't have type compatibility with Writer or PrintWriter.

// Encoding again very important to match that of your output.
PrintStream print = new PrintStream(os, true, "utf-8");

这篇关于如何在同一个servlet请求中使用getOutputStream()和getWriter()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆