Tuesday, April 15, 2008

The Servlet Class Hierarchy

The Servlet Class Hierarchy
The most basic servlet definitions live in the javax.servlet package and consist of a number of interfaces.
  • The ServletContext interface provides a means for servlets to communicate with the surrounding Web server or application server. This communication can take the form of requests for system resources, reports written by the servlet to a log file, and so on. Indirectly, the ServletContext also allows servlets to communicate with one another, primarily by sending requests to other pages. This is how the jsp:forward and jsp:include tags are implemented, as will be seen shortly. ServletContext is implemented by people writing the Web or application server; servlet authors seldom need to use it directly and never need to extend it.
  • The ServletConfig interface provides a mechanism for the web Server to pass initialization information to the servlet's init() method. This information takes the form of pairs of names and values, which are stored in a configuration file called web.xml. If a servlet is going to open a connection to a database, it would not make sense to hard-code the name of the driver class and the database URL in the servlet's code. Doing so would make the servlet more difficult to change if a new database were ever installed. Instead, this information could be sent to the servlet as parameters, and the servlet would use the ServletConfig to retrieve these values and act accordingly. Like ServletContext, this interface is implemented by the authors of the Web server.
  • The Servlet interface defines the three life-cycle methods—init(), service(), and destory()—as well as a handful of others.
  • The ServletRequest and ServletResponse interfaces encapsulate a request to the servlet and a response from the servlet, respectively. Objects that implement these interfaces will be passed to the servlet's service() method. Code within this method can then use the ServletRequest to determine information about the request, such as its origin, the exact data being requested, and so on. Similarly code in the service() method can then use the ServletResponse to return information about the response, as well as the data, such as an HTML page, that comprises the response itself.
  • The javax.servlet package also defines three other classes. Two are the ServletInputStream and ServletOutputStream classes, which servlets use to read and write data, respectively. The third class, GenericServlet, implements both the Servlet and ServletConfig interfaces and forms the basis for most real servlets.

No comments: