Understand Servlet and its working - BEHIND JAVA

Understand Servlet and its working

Share This

Servlets are mainly used to create web applications. We can't run the Servlet program like a standalone program. Servlets are only run inside a web container (like tomcat, jetty, JBoss...etc). Also, another advantage of Servlet is that it will respond to the HTTP requests. Below shows a diagrammatic representation of that.

Start with a Program

To get a basic knowledge of Servlet, it's better to start with a sample program. I suppose you already installed java JDK in your machine else please install it. Following steps explains the further steps.

Step 1: The Web container is mandatory for Servlet programming. So you must download a web container as the first step. Here I am using Tomcat Server.

Step 2: Next we want to create some Servlet program and deploy it into the web container. Here follows the sample code of a Servlet class

package com.behindjava.servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// For Servlet creation you must need to extend your class with HttpServlet
public class BehindJavaServlet extends HttpServlet {
  private String message;

  public void init(ServletConfig servletConfig) throws ServletException
      //Initialization Method
   this.message = servletConfig.getInitParameter("message");

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
      // Setting the response content type

      //Adding the string "Behind Java Example" as h1 text with the servlet response
      PrintWriter out = response.getWriter();
      out.println("<h1>" + "Message is --- "+ message + "</h1>");
  public void destroy()
      // Additional destroy actions.

Lets analyse the above class

For creating a Servlet class we need to extend that class with HttpServlet Class (In above code also we are extending our class with HttpServlet class). What is the importance of HttpServlet Class?

We are creating Servlet for java web application. In the case of web application browsers are mainly used in client side. So for browsers they are mainly communicated to the server via HTTP Protocol. So HttpServlet is a java implemented class which handle the HTTP Request that's why for creating our own Servlet class we need to extend the HttpServlet class. In HttpServlet contains the separate methods for handling different types of HTTP requests like GET, POST, PUT, HEAD...etc.

How HttpServlet class looks like?

HttpServlet is an abstract class which extends GenericServlet class and it implements the Serializable interface. If you find the source code of HttpServlet class it contains no abstract methods but it is an abstract class because this class created according to template method design pattern. The methods specific for HTTP request type (like doGet(), doPost(),doPut()...etc) have default behaviours of returning a HTTP 405 Method Not Implemented error. If those methods were all abstract, you would be forced to override them all, even though your business requirements don't need it at all.

What is GenericServlet and what is the use of it?

GenericServlet class is an abstract class which implements Servlet interface, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method. It is a protocol independent class. So you can implement your own protocol supporting class by extending this class and overriding the service method inside this class. Service method main method which provides service for the incoming request. It is invoked at each time when the user requests for a servlet.

I think you got a good understanding about HttpServlet class from above answers. If you find my above example you will get some overrided method implementations like init(), doGet(), destroy() lets look into its order of execution.

What is the order of execution of init(), doGet(), destroy() methods?

In a Servlet life cycle mainly contains 5 steps which follow in the following diagram

When a Servlet instance is created the init() method become fired. The method init() allows Servlet to initialize itself before the first request is processed. You can specify init parameters to the servlet in the web.xml file.

For every request received to the servlet, the servlets service() method is called. For HttpServlet subclasses, one of the doGet(), doPost() etc. methods are typically called. As long as the servlet is active in the servlet container, the service() method can be called.

When a servlet is unloaded by the servlet container, its destroy() method is called. This step is only executed once, since a servlet is only unloaded once.

So lets go to the remaining steps

Step 3: Create the deployment descriptor file

What is deployment descriptor?

The web.xml file is actually known as deployment descriptor file. This file is an XML document that defines everything about your application that a server needs to know like servlets and other components like filters or listeners, initialization parameters, container-managed security constraints, resources, welcome pages, etc.

For our sample application the web.xml file looks like follows

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"


        <param-value>Namaste BehindJava</param-value>


Here we are creating the BehindJava servlet and mapping the BehindJavaServlet class to that servlet (this is done between <servlet> and </servlet>). Also this servlet become invoked when you request the url /behindjava (this is done between <servlet-mapping> and <servlet-mapping> tags)

Step 4: Creation of folder structure. In above we created a Servlet class and currosponding deployment descriptor file. Now we need to deploy the application into the tomcat (web container). Before that we need to create a directory structure for deployment file. the directory structure looks like follows

Step 5: Start tomcat and run the url. The last step is deploy the folder structure into webapps folder of tomcat and start start tomcat. Then request the url http://localhost:8080/SampleServlet/behindjava It results a page looks like follows


  1. Software developers to create stunning mobile application with ease. Further, they can make use of this platform at free of cost. Java Course in Chennai | Best JAVA Training in ChennaiThanks for your informative post on Java application development. This open source platform assists

    1. Hibernate Online Training Hibernate Online Training Hibernate Training in Chennai Hibernate Training in Chennai Java Online Training Java Online Training

      Hibernate Training Institutes in ChennaiHibernate Training Institutes in Chennai Java Online Training Java Online Training Java Online Training Java Online Training

    2. Java Training Institutes Java Training Institutes Java EE Training in Chennai Java EE Training in Chennai Java Spring Hibernate Training Institutes in Chennai J2EE Training Institutes in Chennai J2EE Training Institutes in Chennai Core Java Training Institutes in Chennai Core Java Training Institutes in Chennai

  2. Hello admin, thank you for your informative post on hadoop training in Chennai. It helped a lot in training my students during our hadoop training Chennai sessions. We at Fita, provide big data training in Chennai for students who are interested in choosing a career in big data.

  3. In java programming the servlets concept is tough but you have clearly explained the topic thanks for sharing this information.

    informatica training in chennai

  4. you have discussed about genericservelet in your post, it was good to read, keop updates with more information.
    Best JAVA Training in Chennai|JAVA Training


  5. These provided information was really so nice,thanks for giving that post and the more skills to develop after refer that post. Your articles really impressed for me,because of all information so nice.

    SAP training in Chennai

  6. interesting blog..
    SEO training in hyderabad by experts in digital markeing And by prosessional experts in seo.All the training by placement and also guide by the professionals.Best SEO training in hyderabad

  7. Hi Admin, I went through your article and it’s totally awesome. You can consider including RSS feed for easy content sharing, So that you can drive huge traffic to your blog.
    Hadoop Training Chennai|Big Data Training|Hadoop Training in Chennai

  8. Hi, This article taught me more about servlet working process, Thanks for Sharing...
    JAVA Training in Chennai|JAVA Course in Chennai

  9. Excellant content. To know the details and importance of python course visit below. Python is an object oriented high level programming language which is built in data structures combined with dynamic typing and dynamic binding making it very attractive for rapid application development.
    Python Training in Chennai | Python Course in Chennai

  10. Much obliged to you for requiring significant investment to give us a portion of the valuable and restrictive data with us.
    Hibernate Training in Chennai | Hibernate Training Chennai | Spring and Hibernate Training in Chennai

  11. Hi, Really your post was very informative. Today's internet era learn Hadoop Online Training will helps you to reach your goal.Selenium Online Training

  12. Nice sharing. R is a language and environment for statistical computing and graphics. Want to make a career in R Programming. Learn R Programming Online Training course @ GangBoard. We are the best provider of online training on evergreen technologies.

  13. Excellent post! Thank you for Sharing. We are the best erp software providers in chennai. For more details call +91 9677025199 or email us on info@bravetechnologies.in ERP in Chennai | ERP Providers in Chennai

  14. Thank you for Sharing. I'm working in brave technologies private limited, We are the best erp software developers based in chennai. erp providers in chennai

  15. Thank you for this valuable information. Get your business to the next level in simple steps. erp in chennai | erp for automotive industry chennai

  16. Thanks for sharing this information. This is very useful. Thanks mate.
    Web D School

  17. thank you for sharing....now this is the time to lead your life then learn.we provide DotNet certified professionals with more real-time experience in live projects.
    Selenium Training in Chennai
    Dot Net Training in Chennai
    Dot Net Training in Chennai

  18. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

  19. The Spring Framework is a lightweight framework for developing Java enterprise applications. It provides high performing, easily testable and reusable code. Spring handles the infrastructure as the underlying framework so that you can focus on your application.Spring is modular in design, thereby making creation, handling and linking of individual components so much easier. Spring implements Model View Container(MVC) design pattern.
    spring mvc form example

  20. It is a one of the great discussion which is very essential for me as well. I must follow the handy discussion and sure that the content will be very useful to me as well. Keep it up. 
    Six Sigma Certification Training in Chennai | Linux Certification Training in Chennai | Microsoft Certification Training in Chennai

  21. Interesting post! This is really helpful for me. I like it! Thanks for sharing!

    Webseiten Gestaltung L├╝denscheid

  22. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing..
    Android Training in Chennai
    Ios Training in Chennai

  23. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information, this is useful to me…
    Java Training Institute in Chennai | DotNet Training Institute in Chennai | Web Designing Training Institute in Chennai

  24. Good post and I like it very much. By the way, anybody try this app development company for iOS and Android? I find it is so professional to help me boost app ranking and increase app downloads.

  25. Interesting post! This is really helpful for me. I like it! Thanks for sharing!
    No.1 MBA Project Center in Chennai | No.1 MBA Project Center in Velachery

  26. really enjoyed while reading your article, the information you have delivered in this post was damn good. Keep sharing your post with efficient news.
    Java Training Center in Chennai | Best J2EE Training Center in Chennai | No.1 Java Training Institution in Velachery | Core Java Training in Chennai

  27. Interesting post! This is really helpful for me. I like it! Thanks for sharing!
    Mobile application developers in Chennai | PHP developers Chennai

  28. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

    data science training in chennai

  29. Thank You for sharing your article, This is an interesting & informative blog. It is very useful for the developer like me. Kindly keep blogging.
    BE/B.Tech Project Center in Chennai | ME/M.Tech Project Center in Chennai | Final Year Project Center in Chennai

  30. your blog contain very useful information and good points were stated in the blog, keep ongoing such a nice blog. Graphic Design Training in Chennai | Multimedia Training Institute in Chennai | Adobe Photoshop Training in Chennai

  31. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly. 
No.1 Software Testing Training Institute in Chennai | Best Selenium Training Institute in Chennai | Java Training in Chennai

  32. You made some good points there. I did a search on the topic and found most people will agree with your blog.
    ME/M.Tech Project Center in Chennai | ME/M.Tech Project Center in Velachery

  33. Nice blog..The information you shared is very effective for learners I have got some important suggestions from it.. RPA Training Institute in Chennai | UI Path Training Institute in Chennai | Blue Prism Training Institute in Chennai


  34. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.


  35. Thanks for sharing this niche useful informative post to our knowledge.
    brochure designers in chennai | brochure design company in chennai

  36. I read this article. I think You put a lot of effort to create this article. I appreciate your work.
    Dissertation Writing Services