Chapter 5. Sending HTML Information

In the previous chapter, we learned that a servlet has access to all sorts of information—information about the client, about the server, about the request, and even about itself. Now it’s time to look at what a servlet can do with that information, by learning how it sets and sends information.

The chapter begins with a review of how a servlet returns a normal HTML response, fully explaining some methods we glossed over in previous examples. Next we cover how to reduce the overhead involved in returning a response by keeping alive a connection to the client. Then we explore the extra things you can do with HTML and HTTP, including using support classes to objectify the HTML output, returning errors and other status codes, sending custom header information, redirecting the request, using client pull, detecting when the user disconnects, and writing data to the server log.

The Structure of a Response

An HTTP servlet can return three kinds of things to the client: a single status code, any number of HTTP headers, and a response body. A status code is an integer value that describes, as you would expect, the status of the response. The status code can indicate success or failure, or it can tell the client software to take further action to finish the request. The numerical status code is often accompanied by a “reason phrase” that describes the status in prose better understood by a human. Usually, a status code works behind the scenes and is interpreted ...

Get Java Servlet Programming 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.