What Are Java Servlets?

Servlets are server side Java classes that add functionality to a web server in a manner similar to the way applets add functionality to a browser. Servlets can be used as a replacement for CGI scripts (or ASP scripts) and they support the standard request/response computing model used by web servers. In this request/response model, a client sends a request message to a server and the server responds by sending back a reply message (usually as HTML).

Servlets run on the web server platform as part of the same process as the web server itself. The web server is initializes, invokes, and destroys each servlet instance. The web server communicates with servlets via a simple interface: javax.servlet.Servlet. This interface defines three main methods:

  init() //invoked on servlet startup, put init code here
  service() //each client request invokes this method
  destroy() //put cleanup code here

To write a servlet, you can simply extend the Servlet class and implement the three main methods. More commonly, however, you would extend the HttpServlet class which has http support built in, making it easy to access request and response objects. When you extend HttpServlet, you can write code for a doGet() and/or doPost() method.

For more information on servlets, go to Sun Microsystem's servlet page

Example 1: Design Your Own Webpage Servlet

Example 2: Guest Book Servlet

Example 3: mySQL Servlet (reads records from mySQL database)

 

   
Website copyright © 2002, SoftTech Design, Inc. All rights reserved worldwide.