Java Reference
In-Depth Information
This example proves that the doGet is called when the servlet is requested by the browser. However, the servlet
did not insert any HTML into the response object; therefore, the RAD browser window displays a blank page. Our next
step is to change MyServlet to insert HTML into the response object.
Working with Response Objects
As mentioned, response objects can hold HTML. However, there are syntax rules that must be followed and we will
need several objects to change the response object. Fortunately, we can import one of the Java classes we'll need and
the response object comes with several useful methods that will help us with the other requirements.
Response objects have a property called content type. Content type is used by the browser to determine how to
handle the response. For instance, if the content type indicates that the response contains HTML, the browser will
read the HTML and display it. If the response's content type specified an Access database file, the browser would
prompt to see if the user wanted to display or download the file.
So, for our example, the servlet needs to set the content type to indicate HTML. The content type property
is modified by the response object's setContentType method. The correct syntax is:
responseVariable .setContentType("text/html");
Once the content type has been specified, we can start writing the HTML to the response object. We will need two
objects to do this: a PrintWriter and an OutputStream . A print writer converts primitives and reference variables into
text. For example, a String variable points to a String object. If you pass a String variable to a print writer, the print
writer will extract the text from the String object. Similarly, the print writer will convert primitive variables to text
values (see Figure 8-20 ). Getting the information into text format is only half the battle. The text has to be converted
into a binary stream (i.e., a set of zeros and ones that the browser can recognize). An OutputStream object converts
the text to a binary stream and this binary stream is written to the response object.
Figure 8-20.
Now, the tricky part.
When a print writer is created, an OutputStream object must be passed to the print writer. This means that an
output stream must be created before the print writer. Response objects have a getOutputStream method that creates
an output stream that is already associated with the response object (i.e., the output stream will automatically write
to that particular response object). In other words, you don't have to create an output stream and then tie it to the
response object. The following statement:
PrintWriter out = new PrintWriter(resp.getOutputStream());
will:
Get an output stream from the response object
Create a
PrintWriter object
Pass the output stream to the print writer
Assign the print writer to a
PrintWriter variable called “out”
 
Search WWH ::




Custom Search