天天看點

Servlet生命周期例子

public class TestLifeCycleServlet extends HttpServlet { 

  public TestLifeCycleServlet(){ 

    System.out.println("constructor"); 

  } 

  @Override 

  public void destroy() { 

    System.out.println("destroy"); 

  public void init(ServletConfig config) throws ServletException { 

    System.out.println("init"); 

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 

      throws ServletException, IOException { 

    System.out.println("doGet"); 

  protected void doPost(HttpServletRequest req, HttpServletResponse resp) 

    this.doGet(req, resp); 

<servlet> 

    <servlet-name>testlife</servlet-name> 

    <servlet-class> 

      com.dvnchina.test.TestLifeCycleServlet 

    </servlet-class> 

  </servlet> 

  <servlet-mapping> 

    <url-pattern>/testlife</url-pattern> 

  </servlet-mapping> 

constructor

init

doGet

destroy

現在分析一下這個結果。

從例子可以看出servlet的生命周期為:             

執行個體化->初始化(init)->調用執行個體doGet方法->銷毀(destroy)

并且我們通路了3次servlet,而構造函數,init()方法,destroy()方法都隻調用了一次,這說明隻執行個體化了一次servlet。servle容器對于一個servlet隻管理一個執行個體,每次用戶端對這個servlet發送請求時,都是調用這個servlet的執行個體。

本文轉自 yzzh9 51CTO部落格,原文連結:http://blog.51cto.com/java999/163702,如需轉載請自行聯系原作者

繼續閱讀