web.xml中listener的作用及使用

來源:互聯網
上載者:User

一.WebContextLoaderListener 監聽類
它能捕捉到伺服器的啟動和停止,在啟動和停止觸發裡面的方法做相應的操作!
它必須在web.xml 中配置才能使用,是配置監聽類的

二.下面是搜集的一些listener方面的知識
簡例一
監聽使用者上線與退出,顯示線上使用者

1、登陸頁面 Login.jsp

<%@page pageEncoding="gb2312" contentType="text/html; charset=gb2312" %>
<%
session=request.getSession(false);
if(session!=null)session.invalidate();
%>
<html>
<head><title></title></head>
<body>
<form action="isOnline.jsp" method="post">
使用者名稱:<input type="text" name="uName"/>
<input type="submit" value="上線">
</form>
</body>
</html>

2、控制頁面(只是為了說明監聽器問題,所以簡單了點...) isOnline.jsp

<%@page pageEncoding="gb2312" contentType="text/html; charset=gb2312" %>
<html>
<head><title></title></head>
<body>
<%
session=request.getSession();
session.setAttribute("userName",request.getParameter("uName"));
response.sendRedirect("showOnline.jsp");
%>
</body>
</html>

3、顯示頁面 showOnline.jsp

<%@page pageEncoding="gb2312" contentType="text/html; charset=gb2312" import="java.util.ArrayList" %>
<html>
<head><title></title></head>
<body>
<%
ArrayList showList=(ArrayList)(getServletContext().getAttribute("list"));
out.print("線上人數 "+showList.size()+"<br>");
for(int i=0;i<showList.size();i++){
out.print(showList.get(i)+"線上"+"<br>");
}
%>
<br>
<a href="Login.jsp">退出</a>
</body>
</html>

4、配置頁面 web.xml

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<listener>
<listener-class>org.xiosu.listener.onlineListener</listener-class>
</listener>
</web-app>

5、監聽器 onlineListener.java

package org.xiosu.listener;

import java.util.ArrayList;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class onlineListener implements HttpSessionListener,
HttpSessionAttributeListener {
// 參數
ServletContext sc;
ArrayList list = new ArrayList();
// 建立一個session時觸發此操作
public void sessionCreated(HttpSessionEvent se) {
sc=se.getSession().getServletContext();
System.out.println("建立一個session");
}
// 銷毀一個session時觸發此操作
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("銷毀一個session");
if (!list.isEmpty()) {
list.remove((String) se.getSession().getAttribute("userName"));
sc.setAttribute("list", list);
}
}
// 在session中添加對象時觸發此操作,在list中添加一個對象
public void attributeAdded(HttpSessionBindingEvent sbe) {
list.add((String) sbe.getValue());
sc.setAttribute("list", list);
}
// 修改、刪除session中添加對象時觸發此操作
public void attributeRemoved(HttpSessionBindingEvent arg0) {
}
public void attributeReplaced(HttpSessionBindingEvent arg0) {
}
}

說明:本例只為簡單介紹監聽器,並未進行安全方面設定。

監聽器也叫Listener,是Servlet的監聽器,它可以監聽用戶端的請求、服務端的操作等。通過監聽器,可以自動激發一些操作,比如監聽線上的使用者的數量。當增加一個HttpSession時,就激發sessionCreated(HttpSessionEvent
se)方法,這樣
就可以給線上人數加1。常用的監聽介面有以下幾個:
ServletContextAttributeListener監聽對ServletContext屬性的操作,比如增加、刪除、修改屬性。
ServletContextListener監聽ServletContext。當建立ServletContext時,激發 contextInitialized(ServletContextEvent
sce)方法;當銷毀ServletContext時,激發contextDestroyed(ServletContextEvent sce)方法。
HttpSessionListener監聽HttpSession的操作。當建立一個Session時,激發session Created(HttpSessionEvent
se)方法;當銷毀一個Session時,激發sessionDestroyed (HttpSessionEvent se)方法。
HttpSessionAttributeListener監聽HttpSession中的屬性的操作。當在Session增加一個屬性時,激發 attributeAdded(HttpSessionBindingEvent
se) 方法;當在Session刪除一個屬性時,激發attributeRemoved(HttpSessionBindingEvent
se)方法;當在Session屬性被重新設定時,激發attributeReplaced(HttpSessionBindingEvent se) 方法。
example:隨伺服器啟動
<web-app>

com.tb.listener.CountStartListener

package com.tb.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import com.tb.timertask.DoCountTask;
public class CountStartListener extends HttpServlet implements ServletContextListener
{
private static final long serialVersionUID = 1824920962239905170L;
public CountStartListener()
{
// TODO Auto-generated constructor stub
}
public void contextDestroyed(ServletContextEvent arg0)
{
// TODO Auto-generated method stub
}
public void contextInitialized(ServletContextEvent arg0)
{
DoCountTask.dotask();
}
}

概述:

Servlet監聽器用於監聽一些重要事件的發生,監聽器對象可以在事情發生前、發生後可以做一些必要的處理。

介面:

目前Servlet2.4和JSP2.0總共有8個監聽器介面和6個Event類,其中HttpSessionAttributeListener與

HttpSessionBindingListener 皆使用HttpSessionBindingEvent;HttpSessionListener和 HttpSessionActivationListener則都使用HttpSessionEvent;其餘Listener對應的Event如下所示:

Listener介面

Event類

ServletContextListener

ServletContextEvent

ServletContextAttributeListener

ServletContextAttributeEvent

HttpSessionListener

HttpSessionEvent

HttpSessionActivationListener

HttpSessionAttributeListener

HttpSessionBindingEvent

HttpSessionBindingListener

ServletRequestListener

ServletRequestEvent

ServletRequestAttributeListener

ServletRequestAttributeEvent

分別介紹:

一 ServletContext相關監聽介面

補充知識:

通過ServletContext 的執行個體可以存取應用程式的全域對象以及初始化階段的變數。

在JSP檔案中,application 是 ServletContext 的執行個體,由JSP容器預設建立。Servlet 中調用 getServletContext()方法得到 ServletContext 的執行個體。

注意:

全域對象即Application範圍對象,初始化階段的變數指在web.xml中,經由<context-param>元素所設定的變數,它的範圍也是Application範圍,例如:

<context-param>

<param-name>Name</param-name>

<param-value>browser</param-value>

</context-param>

當容器啟動時,會建立一個Application範圍的對象,若要在JSP網頁中取得此變數時:

String name = (String)application.getInitParameter("Name");

或者使用EL時:

${initPara.name}

若是在Servlet中,取得Name的值方法:

String name = (String)ServletContext.getInitParameter("Name");

1.ServletContextListener:

用於監聽WEB 應用啟動和銷毀的事件,監聽器類需要實現javax.servlet.ServletContextListener 介面。

ServletContextListener 是 ServletContext 的監聽者,如果 ServletContext 發生變化,如伺服器啟動時 ServletContext 被建立,伺服器關閉時 ServletContext 將要被銷毀。

ServletContextListener介面的方法:

void contextInitialized(ServletContextEvent sce)

通知正在接受的對象,應用程式已經被載入及初始化。

void contextDestroyed(ServletContextEvent sce)

通知正在接受的對象,應用程式已經被載出。

ServletContextEvent中的方法:

ServletContext getServletContext()

取得ServletContext對象

2.ServletContextAttributeListener:用於監聽WEB應用屬性改變的事件,包括:增加屬性、刪除屬性、修改屬性,監聽器類需要實現javax.servlet.ServletContextAttributeListener介面。

ServletContextAttributeListener介面方法:

void attributeAdded(ServletContextAttributeEvent scab)

若有對象加入Application的範圍,通知正在收聽的對象

void attributeRemoved(ServletContextAttributeEvent scab)

若有對象從Application的範圍移除,通知正在收聽的對象

void attributeReplaced(ServletContextAttributeEvent scab)

若在Application的範圍中,有對象取代另一個對象時,通知正在收聽的對象

ServletContextAttributeEvent中的方法:

java.lang.String getName()

回傳屬性的名稱

java.lang.Object getValue()

回傳屬性的值

二、HttpSession相關監聽介面

1.HttpSessionBindingListener介面

注意:HttpSessionBindingListener介面是唯一不需要再web.xml中設定的Listener

當我們的類實現了HttpSessionBindingListener介面後,只要對象加入 Session範圍(即調用HttpSession對象的setAttribute方法的時候)或從Session範圍中移出(即調用HttpSession對象的 removeAttribute方法的時候或Session Time out的時候)時,容器分別會自動調用下列兩個方法:

void valueBound(HttpSessionBindingEvent event)

void valueUnbound(HttpSessionBindingEvent event)

思考:如何?記錄網站的客戶登入日誌, 統計線上人數?

2.HttpSessionAttributeListener介面

HttpSessionAttributeListener監聽HttpSession中的屬性的操作。

當在Session增加一個屬性時,激發attributeAdded(HttpSessionBindingEvent se) 方法;當在Session刪除一個屬性時,激發attributeRemoved(HttpSessionBindingEvent se)方法;當在Session屬性被重新設定時,激發attributeReplaced(HttpSessionBindingEvent se) 方法。這和ServletContextAttributeListener比較類似。

3.HttpSessionListener介面

HttpSessionListener監聽 HttpSession的操作。當建立一個Session時,激發session Created(HttpSessionEvent se)方法;當銷毀一個Session時,激發sessionDestroyed (HttpSessionEvent se)方法。

4.HttpSessionActivationListener介面

主要用於同一個Session轉移至不同的JVM的情形。

四、ServletRequest監聽介面

1.ServletRequestListener介面

和ServletContextListener介面類似的,這裡由ServletContext改為ServletRequest

2.ServletRequestAttributeListener介面

和ServletContextListener介面類似的,這裡由ServletContext改為ServletRequest

有的listener可用於統計網站線上人數及訪問量。 如下:

伺服器啟動時(實現ServletContextListener監聽器contextInitialized方法),讀取資料庫,並將其用一個計數變數儲存在application範圍內

session建立時(實現HttpSessionListener監聽器sessionCreated方法),讀取計數變數加1並重新儲存

伺服器關閉時(實現ServletContextListener監聽器contextDestroyed方法),更新資料庫

轉自: http://www.blogjava.net/wx886104/archive/2010/06/01/322419.html

http://hht83.blog.163.com/blog/static/44037112008324232278/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.