Servlet生命周期

10次阅读

共计 2369 个字符,预计需要花费 6 分钟才能阅读完成。

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
但你也可以定义特定异常的特定页面让容器返回。

正文完
 0