過濾器與監聽器

什麼是過濾器
過濾器是向Web應用程序的請求和響應添加功能的Web服務組件
過濾器可以統一的集中處理請求和響應

過濾器的使用步驟
1、建立實現Filter接口的類
2、實現過濾的行爲
3、調用下一個過濾器或Web資源
4、在web.xml中配置過濾器

過濾器映射的Web資源有四種方式
完全匹配:/index.jsp
目錄匹配:/admin/*
擴展名匹配:*.do
全部匹配:/*

過濾器常用的場合
1、對請求、響應進行統一處理
2、對請求進行日誌記錄和審覈
3、對數據進行屏蔽和替換
4、對數據進行加密和解密

監聽器(Web事件模型一部分)
監聽器可以接收事件,並完成相關的處理

實現在線用戶統計的步驟:
1、創建類實現HttpSessionBindingListener接口
2、在valueBound和valueUnbound方法中實現用戶數量的統計
valueUnbound有三種情況將被執行
1)調用使session失效的方法:session.invalidate()
2)session超時
3)調用setAttribute重新設置了別的對象,或是調用removeAttribute移除了這個屬性

3、在web.xml中配置監聽器

常量類定義:

public class Constants {

	public static int ON_LINE_USERCOUNT;
}
通過實現HttpSessionBindingListener實現在線人數統計:

package cn.jbit.test.entity;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import cn.jbit.test.constants.Constants;

public class User implements HttpSessionBindingListener{
	
	private int id;
	private String username;

	public User() {
		super();
	}

	public User(int id, String username) {
		super();
		this.id = id;
		this.username = username;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void valueBound(HttpSessionBindingEvent arg0) {
		//上線人數加1
		Constants.ON_LINE_USERCOUNT++;
	}
	
	public void valueUnbound(HttpSessionBindingEvent arg0) {
		//上線人數減1
		Constants.ON_LINE_USERCOUNT--;
	}
}
通過實現HttpSessionListener接口實現在線人數統計:

package cn.jbit.test.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class UserCountListener implements HttpSessionListener {
	
	//上線用戶人數
	private int userCount = 0;
	
	public void sessionCreated(HttpSessionEvent event) {
		//在線人數加1
		userCount++;
		setContext(event);
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		//在線人數減1
		userCount--;
		setContext(event);
	}
	
	//設置全局在線用戶人數
	private void setContext(HttpSessionEvent event){
		ServletContext application = event.getSession().getServletContext();
		application.setAttribute("userCount", new Integer(userCount));
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章