Servlets Tutorial

Introduction to Servlets

Servlets are Java programs running on a web server that produce results viewed remotely on web server.

  • A Servlet is a Java class that accept a request and generates a response.
  • The Servlets that we are interested in are called HttpServlet.
  • The HttpServlet accepts HTTP request and generates HTTP response.
  • It is important to understand Servlet because they are the underlying implementation of JSPs.

What are Java Servlets?

Servlets are Java technology's answer to the CGI programming. They are programs that run on a Web server and build Web page. Building Web pages on the fly is useful (and commonly done) for a number of reason:

  • The Web page is based on the data submitted by the user. For example the result pages from search engines are generated this way, and programs that process orders for e-commerce sites do this as well.
  • The data alsp changes frequently. For example, a weather-report or news headlines page might build the page dynamically, perhaps returning a previously built page if it is still up to the date.
  • The Web page uses information from corporate databases or other such source. For example, you would use this for making a Web page at an on-line store that lists current prices and number of items in the stock. What are the Advantage of Servlets Over "Traditional" CGI? Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technology. (More importantly, servlet developers get paid more than Perl programmers :-).
  • Efficient. With traditional CGI, a new process is started for the each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution of time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not the heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the for the CGI program is loaded into memory N time. With servlets, however, there are N threads but only a single copy of the servlets class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping the database connections open, and the like.
  • Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding the HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.
  • Powerful. Java servlets let you easily do several things that are difficult or impossible with the regular CGI. For one thing, servlets can talk directly to Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in the standard places. Servlets can also share data among each other, making the useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computation.
  • Portable. Servlets are written in Java and followsss a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can alsp run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on the almost every major Web server.
  • Inexpensive. There are also a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlets support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.
  • Advantages of servlets over CGI processes


    • have significantly less overhead than CGI
    • can inherit processing state between invocation
    • can use concurrency control in the Java to share state at server.

    Servlets compared to CGI programs:

  • are slower only when being initially it is loaded
  • rather faster to run when it is loaded.
  • Servlets can:

  • open a database connection when initially it is loaded
  • share open DB connection with successive invocation
  • CGI programs have to renew the DB connection each time they're run.
  • Servlets can:

  • store state information in the static variables in servlet
  • share access to the state data each time servlet is run
  • control concurrent access to the shared state easily
  • CGI programs lack the common address space to share state easily.
  • Life Cycle of Servlets

    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.

    • 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:
    • 1.javax.servlet.*
    • 2.javax.servlet.http.*

    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 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 client’s IP address by calling the getRemoteAddr method of HttpServletRequest class.

    Following Examples prints the Hello World in the browser

    • import*;
    • 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.