JSP Servlets   «Prev  Next»

Lesson 4Sending GET to the servlet: Applet structure
Objective Design an applet that sends GET to a servlet

Sending GET to Servlet

When the user clicks the Submit button on your applet, it should send a GET or POST request to the servlet. It is tempting to use the same servlet you used with an HTML form, and use the doPost() method to process the POST request. However, the doPost() methods you have used emit an entire page of HTML. Your applet does not render HTML, so the exact same doPost() method will not work for you. Because you will need to rewrite the servlet anyway, it makes sense to write it the easiest way. For the applet to send a GET to the servlet, you will need to create a URL object and open a URL connection. To send a POST is a little more work, because you will have to send request headers separately. You will change the applet and send a GET to the servlet and write doGet() in the servlet. Before you write code to send a GET, you must decide where the code will go. When the user clicks your button, it will trigger an event. You can send the GET in the handler method for that event. In order for your applet to access the text input field and retrieve the name the user typed, you will need to add it as a member variable of the applet class. You will then need to add code to react to a click on the Submit button using Java 1.1 event handling:
  1. Your applet should implement ActionListener.
  2. After adding the button, call button.addActionListener(this) so the applet will be notified when the button is clicked.
  3. Add a method public void actionPerformed(ActionEvent event).
  4. Add code to actionPerformed() to send the GET request to the servlet.

Structure of the Applet

the applet implements ActionListener
  1. the applet implements ActionListener
  2. the text field is a member variable of the applet
  3. override init() to set up the user interface
  4. add a prompt for the user
  5. create and add the input field
  6. create and add the button, then register as a listener
  7. actionPerformed is the only method in the ActionListener interface
  8. you will see the body of this method in another lesson


Reacting to button event using ActionListener

java.awt.event
Interface ActionListener

Here is the Java Source Code for the Applet
Here is the Java Source Code for the Applet

  line 1 the applet implements ActionListener
  line 3 the text field is a member variable of the applet
  line 4 override init() to set up the user interface
  line 6 add a prompt for the user
  line 7-8 create and add the input field
  line 9-11 create and add the button, then register as a listener
  line 13 actionPerformed is the only method in the ActionListener interface
  line 15 you’ll see the body of this method in another lesson


In the next lesson, learn how to how to add code to an applet to send the GET request.