文章目录
- 监听器( listener)
- 对Application内置对象监听的语法和配置
- 对session内置对象监听的语法和配置
监听器( listener)
对象与对象的关系:
继承关联
tomcat一启动创建的顺序:监听器,config,application(全局初始化参数),filter,servlet(有0 )
**概念:**由Java编写的WEB组件,主要完成对内置对象状态的变化(创建,销毁)和属性的变化进行监听,做进一步的处理。
作用:
- 对session内置对象状态的变化(创建,销毁)和属性的变化进行监听
- 对application内置对象状态的变化(创建,销毁)和属性的变化进行监听
对Application内置对象监听的语法和配置
-
ServletContextDemo.java
java">package cn.mldn.lxh.listener ;import javax.servlet.* ;public class ServletContextDemoimplements ServletContextListener,ServletContextAttributeListener {private ServletContext application = null ;// 实现方法public void contextInitialized(ServletContextEvent sce){this.application = sce.getServletContext() ;System.out.println("** 上下文初始化 ...") ;System.out.println("** 当前虚拟目录的绝对路径:"+this.application.getRealPath("/")) ;}public void contextDestroyed(ServletContextEvent sce){System.out.println("** 上下文销毁 ...") ;}public void attributeAdded(ServletContextAttributeEvent scab){System.out.println("** 增加属性:"+scab.getName()+" --> "+scab.getValue()) ;}public void attributeRemoved(ServletContextAttributeEvent scab){System.out.println("** 删除属性:"+scab.getName()+" --> "+scab.getValue()) ;}public void attributeReplaced(ServletContextAttributeEvent scab){System.out.println("** 替换属性:"+scab.getName()+" --> "+scab.getValue()) ;} };/*<listener><listener-class>cn.mldn.lxh.listener.ServletContextDemo</listener-class></listener> */
-
appdemo.jsp
<% getServletContext().setAttribute("username","jack"); //getServletContext().removeAttribute("username"); %> username:<%=getServletContext().getAttribute("username")%>
对session内置对象监听的语法和配置
-
sessiondemo.jsp
<% session.setAttribute("name","jack"); // session.removeAttribute("name") ;//session.invalidate() ; %><h1> name: ${name} </h1>
-
HttpSessionDemo .java
package cn.mldn.lxh.listener ; import javax.servlet.http.* ; public class HttpSessionDemo implements HttpSessionListener,HttpSessionAttributeListener {private HttpSession session ;// 实现方法public void sessionCreated(HttpSessionEvent se){this.session = se.getSession() ;System.out.println("** Session 创建 ....") ;System.out.println("** SessionID --> "+this.session.getId()) ;}public void sessionDestroyed(HttpSessionEvent se){System.out.println("** Session 销毁 ....") ;}public void attributeAdded(HttpSessionBindingEvent se){System.out.println("** Session 增加属性:"+se.getName()+" --> "+se.getValue()) ;System.out.println("** 获得Session "+se.getSession().getId()) ;}public void attributeRemoved(HttpSessionBindingEvent se){System.out.println("** Session 删除属性:"+se.getName()+" --> "+se.getValue()) ;}public void attributeReplaced(HttpSessionBindingEvent se){System.out.println("** Session 替换属性:"+se.getName()+" --> "+se.getValue()) ;} }; /*<listener><listener-class>cn.mldn.lxh.listener.HttpSessionDemo</listener-class></listener> */