JSP Servlets   «Prev  Next»

Lesson 8Reading the servlet response
ObjectiveAdd code to an applet to read the response from a servlet.

Reading Java Servlet Response

There is one piece of this applet that is still missing.
So far you have seen how to:
  1. React to the button click
  2. Get the text from the input field
  3. Build the URL for the GET request, including the parameter
  4. Send the GET to the servlet by opening the URL connection
  5. Code the servlet doGet() to return a string to the applet
  6. Display the string on the surface of the applet

The step that is missing lies between steps 5 and 6. The applet needs to look at the servlet response and extract the string. The MouseOver below shows the code that makes this step happen:

Input Stream Connection
  1. get an input stream from the connection
  2. first spot, get a buffered reader from the input stream reader
  3. Second spot, get an input stream reader from the input stream
  4. Read the reply from the buffered reader
  5. close the input stream from the servlet


Reading Servlet Response
This is Java 1.1 code, and it is not as simple as it could be.
The URLConnection class has a getInputStream() method that returns an InputStream.
You could read one byte at a time from this stream if you wished, but it’s nicer to read a line at a time straight into a String that you can pass to other methods, like setText() for the label.
The InputStream class does not have a function that reads more than a byte, unfortunately.
You can read a whole line with the readLine() method of the BufferedReader class.
You can’t build a BufferedReader from an InputStream, but you can build a BufferedReader from an InputStreamReader, and you can build an InputStreamReader from an InputStream. That is what this code does. The end result is a String (called reply in my example) that you can pass to setText() to change the text of the label.
In the next lesson, review what you have learned in this module.

Reading Servlet Response - Exercise

Try your hand at building an applet and servlet that process a form.
Reading Servlet Response - Exercise

Java Servlets