import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestLifeCycleServlet extends HttpServlet {

@Override
public void init(ServletConfig config) throws ServletException {
   System.out.println("init");
} @Override
public void destroy() {
    try {
          PrintStream out = System.out;
 PrintStream ps = new PrintStream("H:\test.txt");
  System.setOut(ps);
       System.out.println("Servlet已经消亡!");
       System.setOut(out);

} catch (FileNotFoundException e) {
          e.printStackTrace();
}         
} public TestLifeCycleServlet(){
System.out.println("constructor!");
} @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
       System.out.println("doGet");
}

}
结果是:在结束程序运行时,没有test.txt生成。Servlet

解决方案 »

  1.   

    你确定你的Servlet容器卸载了这个Servlet吗?没有的话,是不会调用destroy方法的!
      

  2.   

     你的问题大概有2点:1.destory()是servlet将要卸载时由servlet引擎调用,跟楼上的说法一样;2.没有执行到调用txt文件那一行,在执行上一行的时候直接跳过去了
      

  3.   

    目前可以肯定的是销毁方法,肯定不是在service结束的时候立刻调用的