Add 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:
React to the button click
Get the text from the input field
Build the URL for the GET request, including the parameter
Send the GET to the servlet by opening the URL connection
Code the servlet doGet() to return a string to the applet
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:
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 its 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 cant 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.