In the previous part we have seen how to send a GET request to the server from your web page. Alright! – Now what ? We will see how the server accept the request with the help of Servlets!

The Lifecycle
When a web server receive the request for a servlet, the server maps the request to a servlet. The servlet is dynamically retrieved and loaded into the address space of server. First the class is loaded and then a single instance is created. Once the servlet instance is loaded, the next job is to initialize the instance. Server do this by invoking the init() lifecycle method of the servlet.

Next, the main responsibility of the servlet comes into picture – which is processing the request. The server process the request by invoking service() life cycle method of the servlet. Servlet can read the data from the request an write a response for the client. The servlet will remain in the server address space and process any other requests – For each request it call the service() method.

The last method is destroy(), which is called by the server when it is time to remove the servlet from the memory. The servlet use this method to clean up the resources like file handles, threads, memory etc.

Interface and Classes
The javax.servlet package provides the Servlet interface and it provides the above discussed lifecycle methods. All of the methods in the Servlet interface except the service() method is implemented by the GenericServlet class which is protocol independent and can handle all type request. If we write our servlet class by extending GenericServlet, we have to override the service() method.

We are not going to develop our GreetingServlet class by extending GenericServlet. Instead of this we will use HttpServlet class – which extends the GenericServlet and implement the service() method and based on the method type it invokes the HTTP specific methods doGet(), doPost() etc. While extending the HttpServlet class, we do have to provide an implementation for any of the doXYZ() methods. Since our GreetingServlet class is supposed to handle the GET request, the below given code shows how to do this

Remember the things we discussed in the last part ? Yes – We have to send a random greetings message to the client. We do three things inside the doGet() method.

  • Set the content type of the response
  • Select message based on the index value passed as the parameter
  • Write down the message in the response by

We will see how this things can be done in the next part. Stay tuned πŸ™‚

Please provide your thoughts and comments, about this topic here πŸ™‚