ServletContextListener的作用
来源:互联网 发布:泗阳网络直通车 编辑:程序博客网 时间:2024/06/05 16:05
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的用法
- JUST SO SO之spring事务
- 设计模式:单例模式
- 代理及注入之org.springframework.beans.factory.BeanNotOfRequiredTypeException
- 2017.04.15【NOIP2017提高组】模拟赛B组
- thinkphp 目录访问安全问题
- ServletContextListener的作用
- 动态规划―最长上升子序列
- 翻转二叉树
- KMP算法详解
- Android从零开搞系列:自定义View(11)使用ViewPager打造轮播广告条
- 练习
- Docker: Ubuntu使用VNC运行基于Docker容器里的桌面系统
- Ubuntu系统下lnmp环境搭建和Nginx多站点配置
- LeetCode-116. Populating Next Right Pointers in Each Node (JAVA)