Our next aim is to create Servlet and see how it respond to client request and send response back to client. So we’ve got two tasks. One – Send a request and two – Receive the response. Here, in this part of “In to the Web” we will see how to create an HTML page which sends a request to the servlet.

When client issue the “localhost:9999/helloworld” URL, the server will return the “index.html” file. This HTML file will display the greeting. When the file first loads, it will send a request to the server targeting GreetingServlet. We will do this with the help of AJAX and jQuery. The response from the servlet is a set of HTML tags. We will insert the HTML tags received in the “index.html” file. The request will have a random number as a parameter, which the servlet use as an index to pick a greeting message.

Hope you are clear with my explanation. So by the end of this part we will see the following.

  • How to send a request to server without refreshing the page
  • How to add a parameter to the request
  • How to add the HTML content in the response to the page

Okay, let me begin 🙂

Generating a random number…

function getRandomInteger(limit) {
 return Math.floor(Math.random() * limit);

The function simply takes an integer limit as an argument and returns any number between 0 and limit – 1. The function includes 0 and excludes limit. We have to use this random number as a parameter in the request. The servlet will use this number to randomly pick a greeting message.

Sending a request and receiving a response…

$(function() {
 // ready handler
 randomInteger = getRandomInteger(3);
 $.get('greetings', {randomNumber: randomInteger}, function(responseData) {

The code here is trying to send a GET request to server. This code will be executed immediately when the document is ready. First the code stores a random number to use in the request. Second it creates the GET request. As a last step it process the response from the server.

The first argument of the get() function is our servlet name. the second parameter is a set of request parameters and third one is a response handler. The response handler here takes an argument which is the response from the server. As already mentioned, the response will be a set of HTML tags. Here we will append this tags to and empty div tag with id=”divMessage” defined in the HTML page.

The complete source code of “index.html” is given below 🙂


Yes, we saw “How to send a request and How to process the response” 🙂

What is next ?? We will see how to develop the Servlet in the upcoming part. Stay tuned 🙂