Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Stardeveloper RSS Feed
Newsletter
Enter your email address below to be informed every time a new article is posted at Stardeveloper.com:

You can follow Faisal Khan on Twitter
Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (10)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)
Log In
UserName Or Email:

Password:

Auto-Login:

Miscellaneous Links
  Submit Article

Hosted by Securewebs.com
 
Home : J2EE : Servlets : Examining Java Servlets in detail. Servlet life cycle, HttpServlet class, ServletConfig and ServletContext Objects
 

Examining Java Servlets in detail. Servlet life cycle, HttpServlet class, ServletConfig and ServletContext Objects

by Faisal Khan.Follow Faisal Khan on Twitter

Overview
This article builds on the first article ' Introduction to Servlets, Your first Java Servlet' to examine Servlets in more detail. In this article we will learn what is Servlet life cycle and how Servlet Container and Servlets interact with each other. We have already learned about init() and destroy() methods in the last article ( see above ) and will learn more about them this time.

As I discussed in my last article, you will most often than not extending the HttpServlet class to develop your Servlets. Since this is going to be the main class you are going to use, it merits more discussion. We will list it's methods and examine them one by one in detail.

Not to forget two important classes which provide environmental support to your web application; ServletConfig and ServletContext. ServletConfig allows Servlets to obtain Servlet specific configuration information like initialization parameters and ServletContext allows application specific initialization parameters and also provides the ability for application components ( Servlets, JSP pages and Java beans ) to interact with each other. We will be examining them in detail.

Following is a list of topics we'll cover in this article :

Servlet Life Cycle
Servlets are normal Java classes which are created when needed and destroyed when not needed. Since Servlets run within a Servlet Container, creation and destruction of Servlets is the duty of Servlet Container and not yours. Implementing the init() and destory() methods of Servlet interface allows you to be told by the Servlet Container that when it has created an instance of your Servlet and when it has destroyed that instance. An important point to remember is that your Servlet is not created and destroyed for every request it receives, rather it is created and kept in memory where requests are forwarded to it and your Servlet then generates response.

Servlet Initialization
So you have created your Servlet class by extending the HttpServlet class and have placed it in /WEB-INF/classes/ directory of your application. Now when will Servlet Container create an instance of your Servlet? there are two situations :

  • When you have specifically told the Servlet Container to preload your Servlet when the Servlet Container starts by setting the load-on-startup tag to a non-zero value e.g.
    <web-app>
    
      <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>com.stardeveloper.servlets.TestServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
    </web-app>
    So when the Servlet Container starts it will preload your Servlet in the memory.
  • If your Servlet is not already loaded, it's instance will be created as soon as a request is received for it by the Servlet Container.

During the loading of the Servlet into the memory, Servlet Container will call your Servlet's init() method. Since init() is going to be called only once you can put Servlet initialization code in it like getting hold of a database connection or whatever.

Responding to Requests
Once your Servlet is initialized and it's init() method called, any request that the Servlet Container receives will be forwarded to your Servlet's service() method. HttpServlet class breakes this service() method into more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods depending on the type of HTTP request it receives. So in order to generate respose you should override the doGet() or doPost() method as required.

At this moment all the requests will be forwarded to the appropriate doGet() or doPost() or whatever method as required. No new instance will be created for your Servlet.

Servlet Destruction
When your application is stopped or Servlet Container shuts down, your Servlet's destroy() method will be called. This allows you to free any resources you may have got hold of in your Servlet's init() method.

Always Remember
init() and destroy() methods will be called only once during the life time of your Servlet while service() and it's broken down methods ( doGet(), doPost() etc ) will be called as many times as requests are received for them by the Servlet Container.

We have now finished learning about Servlet life cycle and we now know about init() , service() and destroy() methods. We can now move on to learn more about HttpServlet class which almost all of your Servlets will extend.

HttpServlet Class
We know that a Servlet is a simple Java class which must implement javax.servlet.Servlet interface. GenericServlet class provides a default implementation of this interface so that we don't have to implement every method of it. HttpServlet class extends GenericServlet to provide an HTTP protocol specific implementation of Servlet interface. If your Servlet has to work with HTTP protocol you should simply extend HttpServlet class and override the methods you need.

Examining Methods of HttpServlet class
Let's examine the methods which this class provides one by one :

  • init()Called only once during the initialization of the Servlet.
  • destroy()Called only once when Servlet instance is about to be destroyed.
  • service()Do not override this method.
  • doGet(), doPost(), doPut(), doDelete(), doOptions, doTrace()These methods are called according to the type of HTTP request received. Override them to generate your own response.
  • log()Writes messages to the Servlet's log files.
  • getLastModified()Override this method to return your Servlet's last modified date.
  • getServletInfo()Override this method to provide a String of general info about your Servlet such author, version, copyright etc.
  • getServletName()Override this method to return name of the Servlet.
  • getInitParameter(), getInitParameterNames()First one returns value of given initialization parameter, second one returns an Enumeration object containing names of all initialization parameters provided. We have already discussed initialization parameters in our earlier article.

Overview
This article builds on the first article ' Introduction to Servlets, Your first Java Servlet' to examine Servlets in more detail. In this article we will learn what is Servlet life cycle and how Servlet Container and Servlets interact with each other. We have already learned about init() and destroy() methods in the last article ( see above ) and will learn more about them this time.

As I discussed in my last article, you will most often than not extending the HttpServlet class to develop your Servlets. Since this is going to be the main class you are going to use, it merits more discussion. We will list it's methods and examine them one by one in detail.

Not to forget two important classes which provide environmental support to your web application; ServletConfig and ServletContext. ServletConfig allows Servlets to obtain Servlet specific configuration information like initialization parameters and ServletContext allows application specific initialization parameters and also provides the ability for application components ( Servlets, JSP pages and Java beans ) to interact with each other. We will be examining them in detail.

Following is a list of topics we'll cover in this article :

Servlet Life Cycle
Servlets are normal Java classes which are created when needed and destroyed when not needed. Since Servlets run within a Servlet Container, creation and destruction of Servlets is the duty of Servlet Container and not yours. Implementing the init() and destory() methods of Servlet interface allows you to be told by the Servlet Container that when it has created an instance of your Servlet and when it has destroyed that instance. An important point to remember is that your Servlet is not created and destroyed for every request it receives, rather it is created and kept in memory where requests are forwarded to it and your Servlet then generates response.

Servlet Initialization
So you have created your Servlet class by extending the HttpServlet class and have placed it in /WEB-INF/classes/ directory of your application. Now when will Servlet Container create an instance of your Servlet? there are two situations :

  • When you have specifically told the Servlet Container to preload your Servlet when the Servlet Container starts by setting the load-on-startup tag to a non-zero value e.g.
    <web-app>
    
      <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>com.stardeveloper.servlets.TestServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
    </web-app>
    So when the Servlet Container starts it will preload your Servlet in the memory.
  • If your Servlet is not already loaded, it's instance will be created as soon as a request is received for it by the Servlet Container.

During the loading of the Servlet into the memory, Servlet Container will call your Servlet's init() method. Since init() is going to be called only once you can put Servlet initialization code in it like getting hold of a database connection or whatever.

Responding to Requests
Once your Servlet is initialized and it's init() method called, any request that the Servlet Container receives will be forwarded to your Servlet's service() method. HttpServlet class breakes this service() method into more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods depending on the type of HTTP request it receives. So in order to generate respose you should override the doGet() or doPost() method as required.

At this moment all the requests will be forwarded to the appropriate doGet() or doPost() or whatever method as required. No new instance will be created for your Servlet.

Servlet Destruction
When your application is stopped or Servlet Container shuts down, your Servlet's destroy() method will be called. This allows you to free any resources you may have got hold of in your Servlet's init() method.

Always Remember
init() and destroy() methods will be called only once during the life time of your Servlet while service() and it's broken down methods ( doGet(), doPost() etc ) will be called as many times as requests are received for them by the Servlet Container.

We have now finished learning about Servlet life cycle and we now know about init() , service() and destroy() methods. We can now move on to learn more about HttpServlet class which almost all of your Servlets will extend.

HttpServlet Class
We know that a Servlet is a simple Java class which must implement javax.servlet.Servlet interface. GenericServlet class provides a default implementation of this interface so that we don't have to implement every method of it. HttpServlet class extends GenericServlet to provide an HTTP protocol specific implementation of Servlet interface. If your Servlet has to work with HTTP protocol you should simply extend HttpServlet class and override the methods you need.

Examining Methods of HttpServlet class
Let's examine the methods which this class provides one by one :

  • init()Called only once during the initialization of the Servlet.
  • destroy()Called only once when Servlet instance is about to be destroyed.
  • service()Do not override this method.
  • doGet(), doPost(), doPut(), doDelete(), doOptions, doTrace()These methods are called according to the type of HTTP request received. Override them to generate your own response.
  • log()Writes messages to the Servlet's log files.
  • getLastModified()Override this method to return your Servlet's last modified date.
  • getServletInfo()Override this method to provide a String of general info about your Servlet such author, version, copyright etc.
  • getServletName()Override this method to return name of the Servlet.
  • getInitParameter(), getInitParameterNames()First one returns value of given initialization parameter, second one returns an Enumeration object containing names of all initialization parameters provided. We have already discussed initialization parameters in our earlier article.

 ( 2 Remaining ) Next

See all comments and questions (post-ad) posted for this tutorial.


Comments/Questions ( Threads: 4, Comments: 4 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. Retrieve image from MySQL database!
  2. How many times init() will get called in case of instance pool
  3. Report error
  4. calling servlet method from another servlet

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed to.

 
© 1999 - 2009 Stardeveloper.com, All Rights Reserved.