Servlet生命週期
Servlet的生命週期是由它部署的容器控制的。當一個請求對映到一個Servlet,Servlet容器執行下面的步驟。
1如果不存在這個Servlet的例項,容器執行:
a. 載入Servlet類
b. 建立Servlet類例項
c. 通過呼叫init方法初始化Servlet(initialization is covered in Creating and Initializing a Servlet)
2容器呼叫Servlet的service方法,傳入requset和response引數。Service方法會在 Writing Service Methods章節探討。
如果它需要移除這個Servlet,則容器通過呼叫Servlet的destroy方法來完成。更多資訊需要檢視Finalizing a Servlet章節。
管理Servlet生命週期事件
你可以通過定義生命週期事件發生方法的監聽器來監聽Servlet的生命週期並做出反應。使用這些監聽物件,你必須定義並且具體描述這些監聽類。
定義監聽類
你定義的監聽類是必須是監聽介面的一個實現。下面的列表定義了可以監聽的事件和對應的必須實現的規範的介面。當監聽方法被呼叫,它將傳入一個適合該事件的容器的資訊的事件。例如,一個HttpSessionListener介面的方法會被傳入一個HttpSessionEvent,HttpSessionEvent包含了一個HttpSession。
Servlet 生命週期事件列表
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
Web context
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
使用@WebListener註解可以獲取特定web程式的各種事件。使用@WebListener註解的類必須實現下列的介面之一。
javax.servlet.ServletContextListener javax.servlet.ServletContextAttributeListener javax.servlet.ServletRequestListener javax.servlet.ServletRequestAttributeListener javax.servlet..http.HttpSessionListener javax.servlet..http.HttpSessionAttributeListener
處理Servlet異常
Servlet執行時,可能發生任意數量的異常。當一個異常發生時,web容器自動生成包含下述資訊的預設頁面:
A Servlet Exception Has Occurred
但你也可以定義特定異常的特定頁面讓容器返回。