Until now, every servlet we’ve written has returned a standard HTML page. The web consists of more than HTML, though, so in this chapter we’ll look at some of the more interesting things a servlet can return. We begin with a look at why you’d want to return different MIME types and how to do it. The most common use of a different MIME type is for returning an image graphic generated by a servlet (or even by an applet embedded inside the servlet!). The chapter also explores when and how to send a compressed response and examines using multipart responses to implement server push.
People are visually oriented—they like to see, not just read, their information. Consequently, it’s nearly impossible to find a web site that doesn’t use images in some way, and those you do find tend to look unprofessional. To cite the well-worn cliche (translated into programmer-speak), “An image is worth a thousand words.”
Luckily, it’s relatively simple for a servlet to send an
image as its response. In fact, we’ve already seen a servlet
that does just this: the
ViewFile servlet from
Chapter 4. As you may recall, this servlet can
return any file under the server’s document root. When the file
happens to be an image file, it detects that fact with the
method and sets its response’s content type with
before sending the raw bytes to the client.
This technique requires that we already have the needed image files saved on disk, ...