Servlet 生命週期

Servlet 生命週期可被定義爲從創建直到毀滅的整個過程。以下是 Servlet 遵循的過程:
- Servlet 通過調用 init () 方法進行初始化。
- Servlet 調用 service() 方法來處理客戶端的請求。
- Servlet 通過調用 destroy() 方法終止(結束)。
- 最後,Servlet 是由 JVM 的垃圾回收器進行垃圾回收的。

init() 方法
第一次創建 Servlet 時被調用,且只調用一次

public void init() throws ServletException {
  // 初始化代碼...
}

service() 方法
Servlet 容器(即 Web 服務器)調用 service() 方法來處理來自客戶端(瀏覽器)的請求,並把格式化的響應寫回給客戶端。

public void service(ServletRequest request, 
                    ServletResponse response) 
      throws ServletException, IOException{
}

doGet() 方法

public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet 代碼
}

doPost() 方法

public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet 代碼
}

destroy() 方法
destroy() 方法只會被調用一次,在 Servlet 生命週期結束時被調用。destroy() 方法可以讓您的 Servlet 關閉數據庫連接、停止後臺線程、把 Cookie 列表或點擊計數器寫入到磁盤,並執行其他類似的清理活動。
在調用 destroy() 方法之後,servlet 對象被標記爲垃圾回收。destroy 方法定義如下所示:

 public void destroy() {
    // 終止化代碼...
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章