欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JSP監(jiān)聽器用法分析

 更新時(shí)間:2016年08月22日 10:28:46   作者:sir  
這篇文章主要介紹了JSP監(jiān)聽器用法,結(jié)合實(shí)例形式分析了監(jiān)聽器的功能、原理及具體使用技巧,并附帶分析了session創(chuàng)建的原理,需要的朋友可以參考下

本文實(shí)例講述了JSP監(jiān)聽器用法。分享給大家供大家參考,具體如下:

監(jiān)聽器也叫Listener,是servlet服務(wù)的監(jiān)聽器。它可以監(jiān)聽客戶端的請求,服務(wù)端的操作等。比如統(tǒng)計(jì)在線用戶數(shù)量。每當(dāng)增加一個(gè)HttpSession時(shí),就會(huì)觸發(fā)sessionCreate(HttpSessionEvent se)方法,這樣就可以給在線人數(shù)加1.常用的監(jiān)聽器接口如下:

1. ServletContextAttributeListener監(jiān)聽對ServletContext屬性的操作。比如增加,刪除,修改屬性。

2. ServletContextListener監(jiān)聽ServletContext。當(dāng)創(chuàng)建ServletContext時(shí),激發(fā)contextInitialized(ServletContextEvent   sce)方法;當(dāng)銷毀ServletContext時(shí),激發(fā)contextDestroyed(ServletContextEvent   sce)方法。

3. HttpSessionListener監(jiān)聽HttpSession的操作。當(dāng)創(chuàng)建一個(gè)Session時(shí),激發(fā)session   Created(HttpSessionEvent   se)方法;當(dāng)銷毀一個(gè)Session時(shí),激發(fā)sessionDestroyed   (HttpSessionEvent   se)方法。
4. HttpSessionAttributeListener監(jiān)聽HttpSession中的屬性的操作。當(dāng)在Session增加一個(gè)屬性時(shí),激發(fā)attributeAdded(HttpSessionBindingEvent   se)   方法;

當(dāng)在Session刪除一個(gè)屬性時(shí),激發(fā)attributeRemoved(HttpSessionBindingEvent se)方法;

當(dāng)在Session屬性被重新設(shè)置時(shí),激發(fā)attributeReplaced(HttpSessionBindingEvent se) 方法。

一個(gè)在線統(tǒng)計(jì)的例子:

public class ONline implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener(){
private ServletContext application = null;
 public void contextInitialized(ServletContextEvent arg0) {
 //根據(jù)響應(yīng)事件參數(shù)初始化ServletContext
 this.application = arg0.getServletContext();
 //在ServletContext中存放一個(gè)空的用戶信息列表
 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在何時(shí)被創(chuàng)建?

常見的誤解是session在有客戶端訪問時(shí)就被創(chuàng)建,然而事實(shí)是某server端調(diào)用HttpServletRequest.getSession(true)這樣的語句時(shí)才被創(chuàng)建。注意如果jsp頁面沒有顯式的使用<%page session="false"%>來關(guān)閉session,則在jsp頁面編譯成Servlet頁面時(shí)會(huì)自動(dòng)加上HttpServletRequest.getSession(true)這句話。這也是jsp中隱藏對象session的來歷。

希望本文所述對大家jsp程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論