A servlet is a Java program that runs on a Web server. It is similar to an applet, but is processed on the server rather than a client's machine. Servlets are often run when the user clicks a link, submits a form, or performs another type of action on a website.
Both servlets and JSP pages contain Java code that is processed by a Web server. However, servlets are primarily Java programs, while JSP pages are primarily HTML files. In other words, a servlet is a Java program that may contain HTML, while a JSP page is an HTML file that may contain Java code. Additionally, servlets require a specific structure and must contain the following three methods:
The init() method initializes the servlet, allocates memory for the process, and passes any input parameters to the servlet. The service() method, which may also be specified as the doGet(), doPost(), doPut(), or doDelete() method, processes the HTTP request and typically provides a response that is sent to the client's browser. The destroy method may save data to a log file and frees up resources that were used by the servlet.
Servlets are one of many options Web developers can use to create dynamic websites and process data entered by website visitors. Since they are written in Java, servlets provide an easy way for programmers who are already familiar with the Java programming language to create Web applications.
Updated: October 20, 2012