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章节。java
你能够经过定义生命周期事件发生方法的监听器来监听Servlet的生命周期并作出反应。使用这些监听对象,你必须定义而且具体描述这些监听类。web
你定义的监听类是必须是监听接口的一个实现。下面的列表定义了能够监听的事件和对应的必须实现的规范的接口。当监听方法被调用,它将传入一个适合该事件的容器的信息的事件。例如,一个HttpSessionListener接口的方法会被传入一个HttpSessionEvent,HttpSessionEvent包含了一个HttpSession。
Servlet 生命周期事件列表code
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent对象
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent接口
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent生命周期
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent事件
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent部署
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEventservlet
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEventit
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
event:Initialization and destruction
Listener Interface and Event Class:javax.servlet.ServletContextListener and ServletContextEvent
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执行时,可能发生任意数量的异常。当一个异常发生时,web容器自动生成包含下述信息的默认页面:
A Servlet Exception Has Occurred
但你也能够定义特定异常的特定页面让容器返回。