先给测试程序
public class TestLifeCycleServlet extends HttpServlet{
@Override
public void destroy() {
System.out.println("Destroy!");
}
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init!");
}
public TestLifeCycleServlet() {
System.out.println("Constructive!");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet");
response.getWriter().write("<a href='http://www.bjsxt.com'>go</a>");
}
}
Tomcat后台(服务器端)的输出结果:
总结Servlet的生命周期:
访问客户端(http://localhost:8080/testServlet/TestLifeCycleServlet)后,servlet经历了如下生命周期:
1. 通过ClassLoader加载类TestLifeCycleServlet
2. 实例化类new TestLifeCycleServlet,执行构造函数,打印Constructive!
3. 初始化,执行init(),打印init!注意参数是ServletConfig,在这里访问了web.xml配置文件
4. 处理请求,执行doGet()或doPost(),打印doGet
5. 退出服务,执行destroy(),打印destroy!
注意:整个周期中,servlet只加载了一次类TestLifeCycleServlet。因此只要servlet没有关闭,不管多少次刷新访问页面,只调用一次构造函数,一次init(),一次destroy(),而每次刷新访问页面,都会调用一次doGet().