简体   繁体   English

理解 servlet 中的 out.println

[英]understanding out.println in servlets

How in Servlets, out.println writes the html text to container's response object where normally in System.out.println() , it writes the text to the console??在 Servlets 中, out.println如何将 html 文本写入容器的响应对象,通常在System.out.println() ,它将文本写入控制台??

This is creating a problem for me conceptually.这在概念上给我带来了问题。

Neither PrintStream nor PrintWriter is specified in terms of a console. PrintStreamPrintWriter都不是在控制台方面指定的。

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. PrintStream 向另一个输出流添加功能,即方便地打印各种数据值的表示的能力。 PrintStream 打印流

Prints formatted representations of objects to a text-output stream.将对象的格式化表示打印到文本输出流。 PrintWriter 印刷机

They are both about formatting data and passing the formatted data to an output stream.它们都是关于格式化数据并将格式化数据传递到输出流。 Any output stream.任何输出流。 By default, in certain environments, the PrintStream objects initially referenced by each of System.out and System.err send their data to some sort of console, but that is just those particular instances.默认情况下,在某些环境中,最初由System.outSystem.err引用的PrintStream对象将它们的数据发送到某种控制台,但这只是那些特定实例。

Even those can be changed.甚至这些都可以改变。 For example, it can be useful in some types of testing to replace System.out with a PrintStream that sends its data to a ByteArrayOutputStream .例如,在某些类型的测试中用PrintStream替换System.out可能很有用,该PrintStream将其数据发送到ByteArrayOutputStream

It uses a ServletOutputStream from the Javadoc,它使用来自 Javadoc 的ServletOutputStream

Provides an output stream for sending binary data to the client.提供用于向客户端发送二进制数据的输出流。 A ServletOutputStream object is normally retrieved via the ServletResponse.getOutputStream() method.通常通过ServletResponse.getOutputStream()方法检索ServletOutputStream对象。

If you look at System.out you can see that it's a PrintStream which is a different implementation of OutputStream .如果您查看System.out您会发现它是一个PrintStream ,它是OutputStream的不同实现。

If someplace in a servlet an invocation of out.println(...) writes to the response object, then out must be a reference to the response object's OutputStream , or a wrapper stream and it.如果在 servlet 中的某个地方调用out.println(...)写入响应对象,则out必须是对响应对象的OutputStream的引用,或者包装流和它。 If System.out sends output someplace else (as normally it would do) then it is a reference to a different OutputStream .如果System.out将输出发送到其他地方(通常会这样做),则它是对不同OutputStream的引用。

A servlet method's (or any other method's) local variable named out is completely unrelated to System.out , barring you initializing the one as a reference to the other.名为out的 servlet 方法(或任何其他方法的)局部变量与System.out完全无关,除非您将一个初始化为对另一个的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM