ServletContextListener的作用
来源:互联网 发布:东北歌手最火的网络歌 编辑:程序博客网 时间:2024/06/16 19:31
ServletContextListener是对ServeltContext的一个监听.servelt容器启动,serveltContextListener就会调用contextInitialized方法.在方法里面调用event.getServletContext()可以获取ServletContext,ServeltContext是一个上下文对象,他的数据供所有的应用程序共享,进行一些业务的初始化servelt容器关闭,serveltContextListener就会调用contextDestroyed.
实际上ServeltContextListener是生成ServeltContext对象之后调用的.生成ServeltContext对象之后,这些代码在我们业务实现之前就写好,它怎么知道我们生成类的名字.实际上它并不需要知道我们的类名,类里面有是方法.他们提供一个规范,就一个接口,ServeltContextListner,只要继承这个接口就必须实现这个方法.然后这个类在web.xml中Listener节点配置好.Servelt容器先解析web.xml,获取Listener的值.通过反射生成对象放进缓存.然后创建ServeltContext对象和ServletContextEvent对象.然后在调用ServletContextListener的contextInitialized方法,然后方法可以把用户的业务需求写进去.struts和spring框架就是类似这样的实现,我们以后写一些框架也可以在用.
java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package
com.chen;
import
javax.servlet.ServletContext;
import
javax.servlet.ServletContextEvent;
import
javax.servlet.ServletContextListener;
public
class
MyServletContextListener
implements
ServletContextListener{
@Override
public
void
contextDestroyed(ServletContextEvent arg0) {
System.out.println(
"destroyed"
);
}
@Override
public
void
contextInitialized(ServletContextEvent event) {
System.out.println(
"initialized"
);
event.getServletContext().setAttribute(
"user"
,
"admin"
);
}
}<br>
xml配置
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version=
"1.0"
encoding=
"UTF-8"
?>
<web-app xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xmlns=
"http://java.sun.com/xml/ns/javaee"
xmlns:web=
"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id=
"WebApp_ID"
version=
"3.0"
>
<display-name>oa</display-name>
<listener>
<listener-
class
>com.chen.MyServletContextListener</listener-
class
>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
阅读全文
0 0
- ServletContextListener ContextLoaderListener的作用
- ServletContextListener的作用
- 10040---ServletContextListener的作用
- ServletContextListener的作用
- ServletContextListener作用
- ServletContextListener作用
- ServletContextListener作用
- ServletContextListener作用
- ServletContextListener作用
- 关于ServletContextListener的认识以及作用
- ServletContextListener作用、使用详解
- javax.servlet.ServletContextListener 作用
- ServletContextListener的使用
- ServletContextListener的用法
- ServletContextListener的用法
- ServletContextListener的用法
- ServletContextListener的用法
- ServletContextListener的用法
- python unittest测试框架介绍
- 【哈夫曼编码】
- pl查询
- 一元一次方程
- 剑指offer题解C++【5】用两个栈实现队列
- ServletContextListener的作用
- Postman工具——Pre-Request Script、Tests
- Scrapy爬取当当网的商品信息存到MySQL数据库
- apt-get update与apt-get upgrade区别
- nodejs-004JSMath函数/数组/表/字符串/常用接口
- 解决ubuntu+win10双系统循环进入启动界面导致无法启动win10的问题
- LeetCode
- 黑色帽子
- nginx(日志管理之日志的使用、定时任务完成日志切割)