You’ve got two choices for output: characters or bytes

This is just plain old java.io, except the ServletResponse interface gives you only two streams to choose from: ServletOutputStream for bytes, or a PrintWriter for character data.

Note

You MUST memorize these methods

You have to know these for the exam. And it’s tricky. Notice that to write to a ServletOutputStream you write(), but to write to a Print-Writer you... println()! It’s natural to assume that you write to a writer, but you don’t. If you already use java.io, then you’ve been down this road. But if you haven’t, just remember:

println() to a PrintWriter

write() to an ServletOutputStream

Make sure you remember that the method names for getting the stream or the writer both drop the first word in the returned type:

ServletOutputStream response.getOutputStream()

PrintWriter response.getWriter()

You need to recognize WRONG method names like:

image with no caption

PrintWriter

Example:

PrintWriter writer = response.getWriter();

writer.println("some text and HTML");

Use it for:

Printing text data to a character stream. Although you can still write character data to an OutputStream, this is the stream that’s designed to handle character data.

OutputStream

Example

ServletOutputStream out = response.getOutputStream();

out.write(aByteArray);

Use it for:

Writing anything else!

Note

FYI: The PrintWriter actually “wraps” the ServletOutputStream. In other words, the PrintWriter has a reference to the ServletOutputStream and delegates calls to it. There’s just ONE output stream back to the client, but the PrintWriter “decorates” the stream by adding higher-level character-friendly methods.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.