Academic Tutorials

English | French | Portugese | German | Italian
Home Advertise Payments Recommended Websites Interview Questions FAQs
News Source Codes E-Books Downloads Jobs Web Hosting

Servlets Tutorial
Servlets Introduction
Servlets Life Cycle
Handling the Client Request:Form Data
Handling the Client Request: HTTP Request Headers
Accessing the Standard CGI Variables
Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Response Headers
Handling Cookies
Session Tracking
Connecting to database in Servlets
Filters in Servlet
Servlets Summary

HTML Tutorials
HTML Tutorial
XHTML Tutorial
CSS Tutorial
TCP/IP Tutorial
CSS 1.0
CSS 2.0
XML Tutorials
XML Tutorial
XSL Tutorial
XSLT Tutorial
DTD Tutorial
Schema Tutorial
XForms Tutorial
XSL-FO Tutorial
XML DOM Tutorial
XLink Tutorial
XQuery Tutorial
XPath Tutorial
XPointer Tutorial
RDF Tutorial
SOAP Tutorial
WSDL Tutorial
RSS Tutorial
WAP Tutorial
Web Services Tutorial
Browser Scripting
JavaScript Tutorial
VBScript Tutorial
DHTML Tutorial
HTML DOM Tutorial
WMLScript Tutorial
E4X Tutorial
Server Scripting
ASP Tutorial
PERL Tutorial
SQL Tutorial
ADO Tutorial
Apple Script
PL/SQL Tutorial
SQL Server
.NET (dotnet)
.Net Mobile
C# : C Sharp
SVG Tutorial
Flash Tutorial
Media Tutorial
SMIL Tutorial
Photoshop Tutorial
Gimp Tutorial
Gnuplot Programming
GIF Animation Tutorial
Scientific Visualization Tutorial
Web Building
Web Browsers
Web Hosting
W3C Tutorial
Web Building
Web Quality
Web Semantic
Web Careers
Weblogic Tutorial
Web Site Hosting
Domain Name
Java Tutorials
Java Tutorial
JSP Tutorial
Servlets Tutorial
Struts Tutorial
EJB Tutorial
JMS Tutorial
JMX Tutorial
Programming Langauges
C Tutorial
C++ Tutorial
Visual Basic Tutorial
Data Structures Using C
Assembly Language
Forth Programming
Lisp Programming
Data Warehousing
CGI Programming
Emacs Tutorial
Soft Skills
Communication Skills
Time Management
Project Management
Team Work
Leadership Skills
Corporate Communication
Negotiation Skills
Database Tutorials
Operating System
Software Testing
SAP Module
Business Warehousing
SAP Basis
Material Management
Sales & Distribution
Human Resource
Customer Relationship Management
Production and Planning
Networking Programming
Corba Tutorial
Networking Tutorial
Microsoft Office
Microsoft Word
Microsoft Outlook
Microsoft PowerPoint
Microsoft Publisher
Microsoft Excel
Microsoft Front Page
Microsoft InfoPath
Microsoft Access
Financial Accounting
Managerial Accounting
Network Sites

Life Cycle of Servlets

Previoushome Next

Servlets Life Cycle have the following Components:

  • Handled by the servlets container.
  • Create and initialize the servlets.
  • Handle zero or more service call.
  • Destroy and garbage collect the servlets.
  • A single servlets instance to handle every request


The Basic Servlet Architecture or Life Cycle

Servlet container create only one instance of each servlet but the request of each user is handled with a separate thread. Each thread then calls the doGet or doPost methods. This idea is shown in the above Figure-5.

1.The init method of the servlets is called when the servlets is first created and each time the server receives a request for a servlets, the server spawns a new thread calls service method.

2.The service method check the HTTP request type (GET,SET, PUT, DELETE, etc.) and calls doGet, doPost, doPut,doDelete, etc. method as appropriate.

3.Finally, the server may decide to remove a previous loaded servlet. In this case, the server calls destroy method of the servlets.


Before we can start writing the first Servlets, we need to know some basics of HTTP ("HyperText Transfer Protocol"), the protocol which is used by a WWW client (e.g. a browser) to send a request to a Web Server.

HTTP is the request-response oriented protocol. An HTTP request consist of a request method, a URI, header fields and a body (which can be empty). An HTTP response contain a result and again header fields and a body.

The service method of HttpServlet dispatch a request to different Java methods for different HTTP request methods. It recognize the standard HTTP/1.1 methods and should not be overridden in subclasses unless you need to implement additional methods. The recognized methods are GET, PUT,HEAD, POST, DELETE, OPTIONS and TRACE. Other methods are answered with a Bad Request HTTP error. An HTTP method XXX is dispatched to the Java method doXxx, e.g. GET -> doGet. All these method expect the parameters "(HttpServletRequest req, HttpServletResponse res)". The method doOptions and doTrace have suitable default implementations and are usually not overridden. The HEAD method (which is supposed to return the same header lines that a GET method would return, but doesn't include a body) is performed by calling the doGet and ignoring any output that is written by this method. That leaves us with the method doGet doPut doPost and doDelete whose default implementations in HttpServlet return a Bad Request HTTP error. A subclass of HttpServlet overrides one or more of these method to provide a meaningful implementation.

The request data is passed to all the methods through the first argument of type HttpServletRequest (which is a subclass of the more general ServletRequest class). The response can be created with the methods of the second argument of type HttpServletResponse (a subclass of ServletResponse).

When you request a URL in the Web Browser, the GET method is used for the request. A GET request does not have the body (i.e. the body is empty). The response should contain the body with the response data and header fields which describe the body (especially Content-Type and Content-Encoding). When you send an HTML form, either GET or POST action can be used. With the GET request the parameters are end in the URL, with a POST request they are transmited in the body. HTML editors and upload tools use PUT requests to the upload resources to a Web Server and DELETE requests to delete resources.

Servlet Types

  • Classic Servlets-service() Method
  • JSP's-Java Embeded in HTML Templates
  • Http Servlets-doGet & doPost()
  • Visual Servlets-Generated by Visual Age

  • Packages in Servlets

    There are two types of package available in servlets which are as follows:



    Interfaces in javax.servlet.*

  • RequestDispatcher
  • Servlet
  • ServletRequest
  • ServletResponse
  • ServletConfig
  • ServletContext
  • SingleThreadModel

  • classes in javax.servlet.*

  • GenericServlet
  • ServletInputStream
  • ServletOutputStream
  • ServletException
  • UnavailableException

  • Interfaces in javax.servlet.http.*

  • HttpServletRequest
  • HttpServletResponse
  • HttpSessionBindingListener
  • HttpSessionContext
  • HttpSession

  • classes in javax.servlet.http.*

  • Cookie
  • HttpServlet
  • HttpUtils
  • HttpSessionBindingEvent

  • Servlet Scope Objects

    The <minOccurs> indicator specify the minimum number of time an element can occur:

    There are four scope objects in servlets which enables the sharing information between web components. The scope objects and their corresponding Java classes are listed below:

  • Web Context javax.servlet.ServletContext
  • Request javax.servlet.HttpServletRequest
  • Session javax.servlet.http.HttpSession
  • Page javax.servlet.jsp.PageContext
  • You can get the attribute values from servlet scope objects using getAttribute method and set new values of attributes using setAttribute method. For example, you can get the clients IP address by calling the getRemoteAddr method of HttpServletRequest class.

    Following Examples prints the Hello World in the browser

    import javax.servlet.*;
    import javax.servlet.http.*;

    public class HelloWorld extends HttpServlet
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    PrintWriter out = response.getWriter();
    out.println("Hello World");

    To be a servlet, a class should extend the HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find out about the incoming information such as FORM data, HTTP request headers, and the like.

    The HttpServletResponse has method that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlet, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exception, so you are required to include them in the declaration. Also note that you have to import classes in the (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.

    Compiling and Installing the Servlet

    Note that the specific details for installing servlet vary from Web server to Web server. Please refer to your Web server documentation for the definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlet are expected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlets in a separate package (hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and doesn't have a good infrastructure for the "virtual servers" to prevent these conflicts automatically. Thus, actually goes in a subdirectory called hall in the servlets directory.

    Note that setup on most other servers is similar, and the servlets and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to prevent name conflicts with other users.

    If you've never used the packages before, there are two main ways to compile classes that are in packages.

    One way is to set your CLASSPATH to point to directory above the one actually containing your servlets. You can them compile normally from within the directory. For example, if your base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory name) is the hall, and you were on Windows, you'd do:

      DOS> set CLASSPATH=C:\JavaWebServer\servlets;%CLASSPATH%
      DOS> cd C:\JavaWebServer\servlets\hall
      DOS> javac

    The first part, setting CLASSPATH, you probably want to do permanently, rather than each time you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH=..." statement in your autoexec.bat file somewhere after the line that set CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to Start menu, select Settings, select Control Panel, select System, select Environment, then enter the variable and value. Note also that if your package were of the form name1.name2.name3 rather than simply name1 as here, you'd still have the CLASSPATH point to the top-level directory of your package hierarchy (the one containing name1).

    A second way to compile classes that are in packages is to go to directory above the one containing your servlets, and then do "javac directory\" (Windows; note the backslash) or "javac directory/" (Unix; note the forward slash). For example, suppose again that your base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory name) is hall, and you were on Windows. In that case, you'd do following:

      DOS> cd C:\JavaWebServer\servlets
      DOS> javac hall\

    Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash, after directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use the JDK 1.1, many servlet authors stick with JDK 1.1 for portability.

    Finally, another advanced option is to keep source code in a location distinct from the .class files, and use javac's "-d" option to install them in the location the Web server expects.

    Running the Servlet

    With the Java Web Server, servlet are placed in the servlets directory within the main JWS installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory is servlets plural, while URL refers to servlet, singular. Since this example was placed in the hall package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may have slightly different conventions on where to install servlets and how to invoke them. Most server also let you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-file.html. The process for doing this is completely server-specific; check your server's documentation for the details.

    A Servlet that Generates HTML

    Most servlet generate HTML, not plain text as in the previous example. To do that, you need two additional steps: tell the browser that you're sending back HTML, and modify the println statements to build a legal Web page. The first step is done by setting Content-Type response header. In general, headers can be set via the setHeader method of HttpServletResponse, but setting the content type is such a common task that there is also a special setContentType method just for this purpose. Note that you need to set the response headers before actually returning any of the content via the PrintWriter. Here's an example:

    The following program called will print Hellow WWW in the browser in the HTML format.

    package hall;

    import javax.servlet.*;
    import javax.servlet.http.*;

    public class HelloWWW extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n" +
    "<HTML>\n" +
    "<HEAD><TITLE&ht;Hello WWW</TITLE></HEAD>\n" +
    "<BODY>\n" +
    "<H1>Hello WWW</H1>\n" +


    Be the first one to comment on this page.

      Servlets Tutorial eBooks

    No eBooks on Servlets could be found as of now.

     Servlets Tutorial FAQs
    More Links » »
     Servlets Tutorial Interview Questions
    More Links » »
     Servlets Tutorial Articles
    More Links » »
     Servlets Tutorial News
    More Links » »
     Servlets Tutorial Jobs
    More Links » »

    Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
    • blinkbits
    • BlinkList
    • blogmarks
    • co.mments
    • connotea
    • digg
    • Fark
    • feedmelinks
    • Furl
    • LinkaGoGo
    • Ma.gnolia
    • NewsVine
    • Netvouz
    • RawSugar
    • Reddit
    • scuttle
    • Shadows
    • Simpy
    • Smarking
    • Spurl
    • TailRank
    • Wists
    • YahooMyWeb

    Previoushome Next

    Keywords: servlets lifecycle,servlet lifecycle,jsp lifecycle,struts lifecycle,ejb lifecycle,servlets tutorial,java servlets,j2ee servlets

    HTML Quizzes
    HTML Quiz
    XHTML Quiz
    CSS Quiz
    TCP/IP Quiz
    CSS 1.0 Quiz
    CSS 2.0 Quiz
    HLML Quiz
    XML Quizzes
    XML Quiz
    XSL Quiz
    XSLT Quiz
    DTD Quiz
    Schema Quiz
    XForms Quiz
    XSL-FO Quiz
    XML DOM Quiz
    XLink Quiz
    XQuery Quiz
    XPath Quiz
    XPointer Quiz
    RDF Quiz
    SOAP Quiz
    WSDL Quiz
    RSS Quiz
    WAP Quiz
    Web Services Quiz
    Browser Scripting Quizzes
    JavaScript Quiz
    VBScript Quiz
    DHTML Quiz
    HTML DOM Quiz
    WMLScript Quiz
    E4X Quiz
    Server Scripting Quizzes
    ASP Quiz
    PERL Quiz
    SQL Quiz
    ADO Quiz
    CVS Quiz
    Python Quiz
    Apple Script Quiz
    PL/SQL Quiz
    SQL Server Quiz
    PHP Quiz
    .NET (dotnet) Quizzes
    Microsoft.Net Quiz
    ASP.Net Quiz
    .Net Mobile Quiz
    C# : C Sharp Quiz
    ADO.NET Quiz
    VB.NET Quiz
    VC++ Quiz
    Multimedia Quizzes
    SVG Quiz
    Flash Quiz
    Media Quiz
    SMIL Quiz
    Photoshop Quiz
    Gimp Quiz
    Matlab Quiz
    Gnuplot Programming Quiz
    GIF Animation Quiz
    Scientific Visualization Quiz
    Graphics Quiz
    Web Building Quizzes
    Web Browsers Quiz
    Web Hosting Quiz
    W3C Quiz
    Web Building Quiz
    Web Quality Quiz
    Web Semantic Quiz
    Web Careers Quiz
    Weblogic Quiz
    SEO Quiz
    Web Site Hosting Quiz
    Domain Name Quiz
    Java Quizzes
    Java Quiz
    JSP Quiz
    Servlets Quiz
    Struts Quiz
    EJB Quiz
    JMS Quiz
    JMX Quiz
    Eclipse Quiz
    J2ME Quiz
    JBOSS Quiz
    Programming Langauges Quizzes
    C Quiz
    C++ Quiz
    Visual Basic Quiz
    Data Structures Using C Quiz
    Cobol Quiz
    Assembly Language Quiz
    Mainframe Quiz
    Forth Programming Quiz
    Lisp Programming Quiz
    Pascal Quiz
    Delphi Quiz
    Fortran Quiz
    OOPs Quiz
    Data Warehousing Quiz
    CGI Programming Quiz
    Emacs Quiz
    Gnome Quiz
    ILU Quiz
    Soft Skills Quizzes
    Communication Skills Quiz
    Time Management Quiz
    Project Management Quiz
    Team Work Quiz
    Leadership Skills Quiz
    Corporate Communication Quiz
    Negotiation Skills Quiz
    Database Quizzes
    Oracle Quiz
    MySQL Quiz
    Operating System Quizzes
    BSD Quiz
    Symbian Quiz
    Unix Quiz
    Internet Quiz
    IP-Masquerading Quiz
    IPC Quiz
    MIDI Quiz
    Software Testing Quizzes
    Testing Quiz
    Firewalls Quiz
    SAP Module Quizzes
    ERP Quiz
    ABAP Quiz
    Business Warehousing Quiz
    SAP Basis Quiz
    Material Management Quiz
    Sales & Distribution Quiz
    Human Resource Quiz
    Netweaver Quiz
    Customer Relationship Management Quiz
    Production and Planning Quiz
    Networking Programming Quizzes
    Corba Quiz
    Networking Quiz
    Microsoft Office Quizzes
    Microsoft Word Quiz
    Microsoft Outlook Quiz
    Microsoft PowerPoint Quiz
    Microsoft Publisher Quiz
    Microsoft Excel Quiz
    Microsoft Front Page Quiz
    Microsoft InfoPath Quiz
    Microsoft Access Quiz
    Accounting Quizzes
    Financial Accounting Quiz
    Managerial Accounting Quiz
    Testimonials | Contact Us | Link to Us | Site Map
    Copyright ? 2008. Academic All rights reserved Privacy Policies | About Us
    Our Portals : Academic Tutorials | Best eBooksworld | Beyond Stats | City Details | Interview Questions | Discussions World | Excellent Mobiles | Free Bangalore | Give Me The Code | Gog Logo | Indian Free Ads | Jobs Assist | New Interview Questions | One Stop FAQs | One Stop GATE | One Stop GRE | One Stop IAS | One Stop MBA | One Stop SAP | One Stop Testing | Webhosting in India | Dedicated Server in India | Sirf Dosti | Source Codes World | Tasty Food | Tech Archive | Testing Interview Questions | Tests World | The Galz | Top Masala | Vyom | Vyom eBooks | Vyom International | Vyom Links | Vyoms | Vyom World | Important Websites
    Copyright ? 2003-2021 Vyom Technosoft Pvt. Ltd., All Rights Reserved.