JSP Servlets   «Prev  Next»

Lesson 5Sending GET to the servlet
Objective Add code to an applet to send a GET request.

Sending GET Request to Java Servlet

When the user clicks the button, your actionPerformed() method will be called by the applet framework. Your code needs to connect to the server with a GET request.
Remember that the browser sends a GET request whenever you type a URL.
This is true also if your applet tries to open a URL: a GET request will be sent for it. You can include parameters in the GET request simply by making them part of the URL, like this:

http://localhost:8080/servlet/FormHello?name=Kate

After the ? comes the parameter name, name, and the value, Kate.
The following diagram contains a the URL with the corresponding parameters.
New URL to create a connection
  1. create a new URL
  2. the URL will start with the applet location
  3. the path to the servlet on the server
  4. a question mark indicates parameters to the GET
  5. the name of the parameter is "name"
  6. the value to be passed is in a variable called "name"
  7. open a connection to this URL
  8. it's a good idea to turn off caching when you create a URL to a servlet, so that even if you send the same parameter (creating an identical URL) your browser gets the HTML from the server instead of your local cache.


Making the connection is simple, thanks to two classes you may have met before: java.net.URL and
java.net.URLConnection
. They represent a URL, like the one above, and a connection to a URL.
You can send the GET request in just three lines! Click the MouseOver button to get an introduction to this code.
These three lines of code create a URL that represents a GET request with a single parameter. This code places the user’s input (in the name variable) into the URL. If you have forgotten how to use the input field that you added as an applet member variable, here's how:
String name = input.getText();

Write the Greeter servlet in the next lesson.