Client/Servlet Interaction
A servlet runs within the context of a server. For the present purposes of this course, that server will be a version of Sun's Java Web Server, an http server that is written in Java and runs as a Java application. Consequently, the Java Server must first be started on some machine accessible through the Internet, just like any other "public" persistent server.
The Java Server is designed as a general framework that supports client connections and then performs various actions in response to client requests (see JavaServer API). However, unlike conventional server designs, most of the services provided by the java Server are implemented as separate modules, called servlets. Thus, the file fetch function is provided by a file access servlet, the CGI interface by a CGI servlet, etc. The important point for our purposes is that the programmer can create new servlets that are supported and run within this same server context.
A servlet is accessed through a URL, just as if it were a file or a CGI program. When a request for a particular servlet is received, the Java Server invokes the servlet as a separate thread of execution. Once started, it can receive environment information as well as client query information similar to that provided through the CGI. It processes the request and returns its data, formatted as HTML, to be included in the body of the HTTP response generated by the Java Server. The servlet is then destroyed by the Java Server.
Servlet Class Hierarchy
Servlets are implemented using the Java Servlet API. All servlets implement the Servlet interface. They normally do this by extending either the GenericServlet class, which implements the Servlet interface, or its subclass, HttpServlet. Since this is a course on WWW-based programming, the discussion here will emphasize HttpServlets.
The relevant classes are organized and contained within two packages: javax.servlet and javax.servlet.http. These packages are not part of the core Java framework, and hence do not begin with the keyword, java. Rather, they are part of the Standard Java Extension API, and hence begin with the keyword, javax. They are provided as add-on packages in conjunction with specific products, such as the Java Server, but they are not included with the standard packages that come with the JDK. This point becomes important when it comes time to compile a Java servlet and will be discussed in the section on Mechanics included in this lesson.
A convenient way to create a servlet meant to be accessed through the Web is to create it as an extension of HttpServlet which is, itself, a subclass of GenericServlet. Since GenericServlet implements the Servlet interface, by inheritance, your servlet will implement that interface, as well. All of this is summarized, below.
Interface javax.servlet.Servletjava.lang.Object | +----javax.servlet.GenericServlet | +----javax.servlet.http.HttpServlet