在doget()方法中调用servlet的destroy方法



我想知道会发生什么,如果我在doget()方法中调用servlet的destroy()方法,假设这是我在dogt()方法本身中的第一条语句。请告知。。

我已经在我的应用程序中进行了尝试,如下所示。。

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();
}
}

但我的应用程序运行良好,但仍然请解释我的逻辑,因为我仍然不清楚。

请告知需要编写哪段代码,即我想覆盖destroy(),以便在执行它时servlet立即被销毁

这当然完全取决于您的实现。如果您还没有覆盖它,那么它几乎什么都不做,因为destroy的实现在HttpServlet中是空的。因此,应用程序继续正常运行。

也许对销毁方法的目的有些混淆目的不是servlet容器提供一些破坏servlet的方法

相反,它允许您提供一些代码,这些代码将在容器调用destroy方法时执行在某些情况下,当容器决定删除servlet时,需要清理资源(例如关闭数据库连接)。容器可以非常独立地删除servlet:例如,如果它内存不足。方法destroy将作为删除的一部分进行调用。

若您的目标是销毁servlet实例,那个么销毁方法不是合适的工具。再一次,调用destroy是删除servlet实例的一部分,而不是删除的原因。正确的工具是从doGet抛出Unavailable Exception(这里不需要destroy方法)。正如Javadoc中所说,无参数构造函数创建这样一个实例,表明servlet永久不可用。此外,容器的任务是对此做出反应,正如servlet规范中所说:

如果不可用异常,servlet容器必须删除servlet从服务,调用其destroy方法,并释放servlet例子容器因该原因拒绝的任何请求必须返回SC_NOT_FOUND(404)响应。

最新更新