Shall we call the destroy()
method from the init()
and service()
methods in a Servlet? I got many confusing answers across the blogs.
As I understand it, when we call the destroy()
method from the init()
it should call and destroy the servlet, if we are going to override the destroy()
in our servlet. Then the servlet will get destroyed.
Is the above understanding right?
None of all is true.
The servlet's destroy()
method is only called by the container whenever it's going to be shutdown. During container's shutdown all servlets will be destroyed. You should not call the method yourself. The destroy()
method just offers you the opportunity to execute some code upon shutdown. For example, to close some external resources which were opened during init()
.
E.g.
private SomeExternalResource someExternalResource;
@Override
public void init() {
someExternalResource = new SomeExternalResource();
}
@Override
public void destroy() {
someExternalResource.close();
}
You do not necessarily need to implement the method when you have nothing to clean up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With