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

问题描述

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

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

推荐答案

您不能同时使用它们.如果您首先执行了 getOutputStream(),那么您就不能在同一个请求中执行 getWriter(),反之亦然.但是,您可以将 ServletOuptputStream 包装在 PrintWriter 中,以获得与 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 或 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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 17:16