Servlets

Servlet LifeCycle
  1. A servlet engine loads and initializes the servlet
  2. The Servlet handles zero or more client requests, each as a separate thread.
  3. The Servlet engine removes the servlet from its memory. Unload sometime occurs when the servlet engine shuts down

  1. Initially when the servlet starts - the servlet initializes using the init() method.
  2. Then client requests are handled.
    The client requests are handled thru the service() method which supports HTTP requests by using the following methods:

    • Overridden methods
      doGet()
      doPost()
      doPut()
      doDelete()

    • Generally not overridden:
      doOption() - handles OPTIONS request. The HTTP Options are determined automatically by this method.
      doTrace() - handles the Trace request. The response typically contains all of the headers in the trace request

  3. When the server removes the servlet it runs the destroy() method.

HTTPServletRequest Object

Provides access to HTTP header data such as:

    Methods:


FOR HTTP POST, PUT and DELETE requests:

The text data is handled by getReader() method that provides you with BufferedReader object to read the raw data.

The binary data is handled in getInputStream() method that provides a ServletInputStream to read the raw data.

HTTPServletResponse Object
    Two ways are available for returning the data from the user:

  1.     getWriter() method returns a writer for text data
  2.     getOutputStream returns a ServletOutputStream for binary data

Close these streams lets the server know that the response is complete.

Debugging Servlets

  1. Look at the HTML Source - to see if the tags are coded properly.
  2. Return error pages to the client - typically send error code -
  3. Look at the server running in command line for any apparent errors when the call to the servlet is made.
  4. HTTPServlet object has a method called log that allows you to log information to the server. Location of the file is specific to Servlet Engines
  5. Print out request data separately
  6. Print out response data separately.
  7. Restarting the webserver is also a good idea: unless the webserver support automatic reload.

Here is a simple example: Responselet.java that accepts data from a simple HTML form form1.html.