JSP监听器用法分析

网络编程 2021-07-05 11:23www.168986.cn编程入门
这篇文章主要介绍了JSP监听器用法,结合实例形式分析了监听器的功能、原理及具体使用技巧,并附带分析了session创建的原理,需要的朋友可以参考下

本文实例讲述了JSP监听器用法。分享给大家供大家参考,具体如下:

监听器也叫Listener,是servlet服务的监听器。它可以监听客户端的请求,服务端的操作等。比如统计在线用户数量。每当增加一个HttpSession时,就会触发sessionCreate(HttpSessionEvent se)方法,这样就可以给在线人数加1.常用的监听器接口如下:

1. ServletContextAttributeListener监听对ServletContext属性的操作。比如增加,删除,修改属性。

2. ServletContextListener监听ServletContext。当创建ServletContext时,激发contextInitialized(ServletContextEvent   sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent   sce)方法。

3. HttpSessionListener监听HttpSession的操作。当创建一个Session时,激发session   Created(HttpSessionEvent   se)方法;当销毁一个Session时,激发sessionDestroyed   (HttpSessionEvent   se)方法。
4. HttpSessionAttributeListener监听HttpSession中的属性的操作。当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent   se)   方法;

当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;

当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

一个在线统计的例子:

public class ONline implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener(){
private ServletContext application = null;
 public void contextInitialized(ServletContextEvent arg0) {
 //根据响应事件参数初始化ServletContext
 this.application = arg0.getServletContext();
 //在ServletContext中存放一个空的用户信息列表
 application.setAttribute("users", new ArrayList());
 }
 public void sessionDestroyed(HttpSessionEvent arg0) {
 List list = (List)application.getAttribute("users");
 String name = arg0.getSession().getAttribute("name").toString();
 list.remove(name);
 application.setAttribute("users", list);
 }
 public void attributeAdded(HttpSessionBindingEvent arg0) {
 List list = (List)application.getAttribute("users");
 if(arg0.getName().equals("name")){
  list.add(arg0.getValue().toString());
 }
 application.setAttribute("users", list);
 }
}

web.xml文件中配置:

<listener>
   <listener-class>package.classname</listener-class>
</listener>

附:session在何时被创建?

常见的误解是session在有客户端访问时就被创建,然而事实是某server端调用HttpServletRequest.getSession(true)这样的语句时才被创建。注意如果jsp页面没有显式的使用<%page session="false"%>来关闭session,则在jsp页面编译成Servlet页面时会自动加上HttpServletRequest.getSession(true)这句话。这也是jsp中隐藏对象session的来历。

希望本文所述对大家jsp程序设计有所帮助。

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by

长沙网络推广|微博营销|长沙seo优化|视频营销|长沙网络营销|微信营销|长沙网站建设|口碑营销|软文营销