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, and we look at how to use response buffering to help this. Then we explore the extra things you can do with HTML and HTTP, including returning errors and other status codes, sending custom header information, redirecting the request, using client pull, handling servlet exceptions, detecting when the user disconnects, and writing data to the server log.

Unlike the first edition, this chapter does not go into detail on generating HTML within servlets. Instead, at the end of the chapter, we introduce the concept of a content-creation architecture, which can be layered on top of servlets and provides a more effective way of generating HTML content. This is an introduction to later chapters in the book in which we discuss a number of individual frameworks.

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, ...

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