Servlets exist in and are managed by the servlet engine in the Application Server. The servlet engine is an internal object that handles all servlet meta functions. These functions include instantiation, initialization, destruction, access from other components, and configuration management. This section covers the following topics:
After the servlet engine instantiates the servlet, the servlet engine calls the servlet’s init() method to perform any necessary initialization. You can override this method to perform an initialization function for the servlet’s life, such as initializing a counter.
When a servlet is removed from service, the servlet engine calls the destroy() method in the servlet so that the servlet can perform any final tasks and deallocate resources. You can override this method to write log messages or clean up any lingering connections that won’t be caught in garbage collection.
When a request is made, the Application Server hands the incoming data to the servlet engine. The servlet engine processes the request’s input data, such as form data, cookies, session information, and URL name-value pairs, into an HttpServletRequest request object type.
The servlet engine also creates an HttpServletResponse response object type. The engine then passes both as parameters to the servlet’s service() method.
In an HTTP servlet, the default service() method routes requests to another method based on the HTTP transfer method: POST, GET, DELETE, HEAD, OPTIONS, PUT, or TRACE. For example, HTTP POST requests are sent to the doPost() method, HTTP GET requests are sent to the doGet() method, and so on. This enables the servlet to process request data differently, depending on which transfer method is used. Since the routing takes place in the service method, you generally do not override service() in an HTTP servlet. Instead, override doGet(), doPost(), and so on, depending on the request type you expect.
To perform the tasks to answer a request, override the service() method for generic servlets, and the doGet() or doPost() methods for HTTP servlets. Very often, this means accessing EJB components to perform business transactions, then collating the information in the request object or in a JDBC ResultSet object.