Servlet生命周期的介绍

本篇文章给大家带来的内容是关于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

但你也可以定义特定异常的特定页面让容器返回。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注编程之家的Java视频教程栏目!

相关文章

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
今天犯了个错:“接口变动,伤筋动骨,除非你确定只有你一个...
Writer :BYSocket(泥沙砖瓦浆木匠)微 博:BYSocket豆 瓣:...
本文目录 线程与多线程 线程的运行与创建 线程的状态 1 线程...