Can we call destroy() method on servlets from service method
By Ramakrishna on Aug 10, 2008 in Servlet Tutorial
we can call the destroy() method. but it works like normal method , for example ,if u have one method in ur servlet class like show(), it acts like show() method. whenever we click on the stop link in manager page of that particular application,then only application will be stopped and it calls the destory method. At that time only the application objects permenantly destroyed.sample code: Try it out..
public class TestServlet extends HttpServlet implements SingleThreadModel
{
public void init()
{
System.out.println(“hello in init”);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
PrintWriter out=response.getWriter();
out.println(“Selected Button Name :”+request.getParameter(“button”));
}
public void destroy()
{ System.out.println(“Hello in destroy”); }
Destroy method is a method where we can provide the actions (to free up the resources) to be performed while the servlet is getting unloaded. In general when a servlet is getting destroyed the servlet container calls this method and also does many other things. So if you want to unload a servlet you have to do all the things the servlet container does including calling the servlet method.
When you directly call the destroy method from service method the method will be successfully called as you are calling the method from same object but you are not doing all the other things the servlet does to unload the servlet. So the servlet will not be unloaded but the destroy method will be called as any other non life cycle method (like display()).
