Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > jsp技巧

JSP监听器用法分析

来源:中文源码网    浏览:231 次    日期:2024-05-18 02:43:17
【下载文档:  JSP监听器用法分析.txt 】


JSP监听器用法分析
本文实例讲述了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文件中配置:

package.classname

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

相关内容