java怎么拦截某个对象
277
2022-09-05
Listener
文章目录
Listener概述基本使用代码实现
Listener概述
Listener 表示监听器,是 JavaWeb 三大组件(Servlet、Filter、Listener)之一。
监听器可以监听就是在 application,session,request 三个对象创建、销毁或者往其中添加修改删除属性时自动执行代码的功能组件。
request 和 session 我们已经了解。而 application 是 ServletContext 类型的对象。
ServletContext 代表整个web应用,在服务器启动的时候,tomcat会自动创建该对象。在服务器关闭时会自动销毁该对象。
JavaWeb 提供了8个监听器:
监听器分类 | 监听器名称 | 作用 |
ServletContext监听 | ServletContextListener | 用于对ServletContext对象进行监听(创建、销毁) |
– | ServletContextAttributeListener | 对ServletContext对象中属性的监听(增删改属性) |
Session监听 | HttpSessionListener | 对Session对象的整体状态的监听(创建、销毁) |
– | HttpSessionAttributeListener | 对Session对象中的属性监听(增删改属性) |
– | HttpSessionBindingListener | 监听对象于Session的绑定和解除 |
– | HttpSessionActivationListener | 对Session数据的钝化和活化的监听 |
Request监听 | ServletRequestListener | 对Ruquest对象进行监听(创建、销毁) |
– | ServletRequestAttributeListener | 对Ruquest对象中属性的监听(增删改属性) |
基本使用
这里面只有 ServletContextListener 这个监听器后期我们会接触到,ServletContextListener 是用来监听 ServletContext 对象的创建和销毁。
ServletContextListener 接口中有以下两个方法
void contextInitialized(ServletContextEvent sce):ServletContext 对象被创建了会自动执行的方法void contextDestroyed(ServletContextEvent sce):ServletContext 对象被销毁时会自动执行的方法
代码实现
接下来我们就以 ServletContextListener 这个监听器为例子:
@WebListener()public class ListenerDemo1 implements ServletContextListener { // ------------------------------------------------------- // ServletContextListener implementation // ------------------------------------------------------- public void contextInitialized(ServletContextEvent sce) { /* This method is called when the servlet context is initialized(when the Web application is deployed). You can initialize servlet context related data here. */ //加载资源 System.out.println("ContextLoaderListener..."); } public void contextDestroyed(ServletContextEvent sce) { /* This method is invoked when the Servlet Context (the Web application) is undeployed or Application Server shuts down. */ //释放资源 }}
启动服务器,就可以在启动的日志信息中看到 contextInitialized() 方法输出的内容,同时也说明了 ServletContext 对象在服务器启动的时候被创建了。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~