JSP Servlets   «Prev  Next»

Lesson 7 Displaying the servlet response
Objective Add code to an applet to display the response from a servlet.

Displaying Java Servlet Response

Displaying Java Servlet ResponseThe applet is really coming together now.
You have seen how to react to the user clicking the button, how to build the URL that will cause the browser to send a GET to the servlet, and how to code the servlet so that it sends back a string in response to the GET.
You might ask, What will the applet do with that string when the servlet sends it back?

There are lots of possibilities.
You could display a message box, change the Enter your name label on the surface of the applet,
or draw some text directly on the surface of the applet.
For the purpose of example, we will create another label, and change the text of this output label from blank to the greeting you get from the servlet. The following SlideShow demonstrates the overall effect.

Applet Servlet 1
1) The applet is preparing to gather information from the user.
Applet Servlet 2
2) The user types Kate and presses the Submit button.
Applet Servlet 3
3) The applet sends the GET request to the servlet, with the parameter
Applet Servlet 4
4) The servlet's doGet() method returns a string
Applet Servlet 5
5) The applet displays the string.

Applet Servlet Interaction
To add another label, I added it as a member variable. In init() I set its value to many spaces.
As part of actionPerformed(), I changed its value with setText().
Here are the relevant changes to the applet
public class Getter extends Applet implements ActionListener{
  private TextField input;
  private Label output = new Label("                                  ");
  public void init() {
   // beginning of init() is unchanged
   add(output);
  }
 // --- actionPerformed  
  public void actionPerformed(ActionEvent event) {
   // send request to servlet and get response into "reply" variable 
            output.setText(reply);
  }
}

More Complex Applet
All the spaces in the initial value of the label are to ensure that enough room is left on the applet surface for the longer strings the label will hold later.
Learn how to read the string from the servlet in the next lesson.

Java Servlets