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:
- Your applet should implement
ActionListener.
- After adding the button, call
button.addActionListener(this)
so the applet will be notified when the button is clicked.
- Add a method
public void actionPerformed(ActionEvent event).
- Add code to
actionPerformed()
to send the GET request to the servlet.
|
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
|
youll see the body of this method in another lesson
|