Reputation: 67
I was wondering what would happen , If I call destroy() method of servlet inside doget() method, lets assume this is my first statement inside doget() method itself.Please advise..
I have tried in my application as shown below..
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
destroy(); //calling destroy
String name=request.getParameter("txtName");
HttpSession ses=request.getSession();
ses.setAttribute("username",name);
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html><head><title>Cookie example</title></head><body>");
out.println("welcome,"+name);
out.println("<br><a href=ck>Take a Tour</a></body></html>");
out.close();
}
}
But my application works fine but still please explain me the logic, as I am still not clear.
Please advise what piece of code is need to be written that is I want to override the destroy() such that upon executing of it servlet get destroyed immediately
Upvotes: 0
Views: 2735
Reputation: 42094
That of course depends perfectly about your implementation. If you haven't overridden it, then it does quite much nothing, because implementation of destroy is empty in HttpServlet. As result application continues to run normally.
Maybe there is some confusion about purpose of destroy method. Purpose is not that servlet container provides some method that destroys servlet.
Instead it gives you possibility to provide some code that will be executed when destroy method is called by container. In some cases there is need to clean resources (closing database connection for example) when container decides to removes servlet. Container can remove servlet quite much independently: for example if it is short of memory. Method destroy
will be called as part of removal.
If your goal is to destroy servlet instance, destroy method is not the right tool. Once again, call to destroy is part of removing servlet instance, not the cause of removal. Right tool is to throw UnavailableException from doGet (no need for destroy method here). As said in the Javadoc, parameterless constructor creates such a instance which indicates that servlet is permanently unavailable. Further it is containers task to react to this, as said in servlet specification:
If a permanent unavailability is indicated by the UnavailableException, the servlet container must remove the servlet from service, call its destroy method, and releasethe servlet instance. Any requests refused by the container by that cause must be returned with a SC_NOT_FOUND (404) response.
Upvotes: 4