Servlets provide a more effective mechanism of achieving the functionality offered by CGI (Common Gateway Interface) scripts. CGI was one of the first techniques for creating dynamic Web pages by allowing the client to kickoff the execution of server-side programs. Servlets provide the same functionality by extending the capabilities of the Web server they run in.
Servlets offer several advantages over CGI scripts. Because servlets run within a Web server, they can take advantage of the functionality offered by the server. On the other hand, each time a CGI script is called from the client, it results in the execution of a new process on the server. For highly interactive environments, this is a performance hog. Servlets also run as threads within Web servers. Once the servlet class is loaded by the server, it can be reused, making servlets more efficient. In addition, servlets are portable across operating systems and servers. Because they are Java classes, they offer the same benefits of portability that Java does. Furthermore, servlets offer a better way of preserving state than CGI does. State between CGI programs is preserved using cookies or some other mechanism. Since a servlet's lifecycle is typically as long as it is loaded by the server, all the state variables are preserved between servlet invocations. Since the Web server manages servlets, the responsibility of thread-pooling and management is shifted to the server instead of the servlet programmer.
CGI is still more popular than servlets because it has a much wider user base and is available on a variety of platforms. However, as server-side Java gains more popularity and servlets are supported by more Web servers, they may prove to be a replacement for CGI. (Also see Tip: "What are Servlets?")