ASP程式員經常要在global.asa檔案內處理Application_start,Session_Start等
事件,如:使用者驗證、重新導向不同編碼頁面等,十分方便,然而一向頗受歡迎的JSP並不很支援這種處理,除了商業化伺服器JRun支援global.jsa以外,竟連應用率極高的開放源碼伺服器Tomcat都不支援,這給JSP的開發造成不小障礙,雖然早期Tomcat(5.0以前版本)下可以通過以下方式實現Session-start事件處理
1. 添加Session
session.put(“bind.listener”,new MyListener(getServletContext())
2. 定義MyListener類
import javax.servlet.http.*;
import javax.servlet.*;
public class MyListener implements HttpSessionBindingListener
{
ServletContext context;
public ODSessionListener(ServletContext context)
{
this.context=context;
}
public void valueBound(HttpSessionBindingEvent event)
{
System.out.println(“bound”);
}
public void valueUnBound(HttpSessionBindingEvent event)
{
System.out.println(“unbound”);
}
}
但處理前提是Session已經建立,並且不能在Session建立時處理驗證等事件,通過研究Servlet 2.4(Tomcat5.0內建)終於找到一種可行方法,實現方法如下:
//---------------------- SessionListener.java----------------------------------------------------
package listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
// ServletRequestListener為Servlet2.4新增介面
import javax.servlet.ServletRequestListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;
public final class SessionListener
implements HttpSessionListener,ServletRequestListener {
private HttpServletRequest request;
public void requestDestroyed(ServletRequestEvent sre) { }
public void requestInitialized(ServletRequestEvent sre)
{
request=(HttpServletRequest)sre.getServletRequest();
}
public void sessionCreated(HttpSessionEvent event) {
String logMsg=event.getSession().getId()
+"' '"+request.getRemoteAddr()
+":"+request.getRemotePort();
log("sessionCreated('" + logMsg + "')");
}
public void sessionDestroyed(HttpSessionEvent event) {
log("sessionDestroyed('" + event.getSession().getId() + "')");
}
private void log(String message) {
System.out.println("SessionListener: " + message);
}
}
在開始接到用戶端請求(requestInitialized)時,獲得當前的HttpRequest對象儲存在私人成員 request 中,這樣在Session建立時可以實現對Session使用者進行驗證,以及關閉Session,限制IP地址訪問等,這裡僅以記錄Session來源為例(SessionListener.java)
編譯這個類後還要在web.xml的host元素內加入以下行:
<listener>
<listener-class>listeners.SessionListener</listener-class>
</listener>
本文適用環境:Tomcat 5.02,J2SE1.41(不支援商務服務器)