Google News
logo
Java Servlets - Interview Questions
Define 'init' and 'destroy' methods in servlets.
Servlets ​​Init Method is used to initialise a Servlet.
 
After the web container loads and instantiates the servlet class and before it delivers requests from clients, the web container initializes the servlet. To customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities, you override the init method of the Servlet interface.
 
Example : 
public class CatalogServlet extends HttpServlet {
private ArticleDBAO articleDB;
public void init() throws ServletException {
articleDB = (ArticleDBAO)getServletContext().
getAttribute("articleDB");
if (articleDB == null) throw new
UnavailableException("Database not loaded");
}
}
When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources or when it is being shut down), the container calls the destroy method of the Servlet interface.
 
The following destroy method releases the database object created in the init method.
public void destroy() {
bookDB = null;
}

 

Advertisement