我们应该从 Servlet 中的 init() 和 service() 方法中调用 destroy() 方法吗?
我们应该从 Servlet 中的 init()
和 service()
方法调用 destroy()
方法吗?我在博客上得到了许多令人困惑的答案。
据我了解,当我们从 init()
调用 destroy()
方法时,如果我们要覆盖 ,它应该调用并销毁 servlet destroy() 在我们的 servlet 中。然后servlet就会被销毁。
上述理解对吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有一个是真的。
Servlet 的
destroy()
方法仅在容器即将关闭时由容器调用。在容器关闭期间,所有 servlet 都将被销毁。您不应该自己调用该方法。destroy()
方法只是为您提供在关闭时执行一些代码的机会。例如,关闭一些在init()
期间打开的外部资源。例如,
当您没有任何东西需要清理时,您不一定需要实现该方法。
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. Thedestroy()
method just offers you the opportunity to execute some code upon shutdown. For example, to close some external resources which were opened duringinit()
.E.g.
You do not necessarily need to implement the method when you have nothing to clean up.
在 java servlet 中,程序员不应调用
destroy()
方法。但是,如果调用它,它就会被执行。但主要问题是,servlet 会被破坏吗?不,不会的。destroy()
方法不会销毁 java servlet。它只是当 Web 容器因任何原因(例如服务器重新启动)而销毁 servlet 时调用的方法(我们可以说是一个事件)。但是,如果您自己调用 destroy() 方法,内容就会被执行,然后相应的过程会继续。针对这个问题,执行destroy(),然后servlet初始化完成。
In java servlet, the
destroy()
method is not supposed to be called by the programmer. But, if it is invoked, it gets executed. But the main question is, will the servlet get destroyed? No, it will not.destroy()
method will not destroy a java servlet. It is just the method(we can say as an event) get called when web container is going to destroy the servlet for any of the reason (like server restart).But if you invoke the
destroy()
method yourself, the content just gets executed and then the respective process continues. With respective to this question, thedestroy()
gets executed and then the servlet initialization gets completed.