向書本學習,還要向?qū)嵺`學習、向生活學習。消化已有知識,
而且要力求有所發(fā)現(xiàn)、有所發(fā)明、有所創(chuàng)造
2019/3/24 8:18:11
ASP程序員經(jīng)常要在global.asa文件內(nèi)處理Application_start,Session_Start等
事件,如:用戶驗證、重定向不同編碼頁面等,十分方便,然而一向頗受歡迎的JSP并不很支持這種處理,除了商業(yè)化服務(wù)器JRun支持global.jsa以外,竟連應用率極高的開放源碼服務(wù)器Tomcat都不支持,這給JSP的開發(fā)造成不小障礙,雖然早期Tomcat(5.0以前版本)下可以通過以下方式實現(xiàn)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已經(jīng)建立,并且不能在Session創(chuàng)建時處理驗證等事件,通過研究Servlet 2.4(Tomcat5.0內(nèi)建)終于找到一種可行方法,實現(xiàn)方法如下:
//---------------------- 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)
深圳市南山區(qū)南山街道南海大道西桂廟路北陽光華藝大廈1棟4F、4G-04
咨詢電話:136 8237 6272
大客戶咨詢:139 0290 5075
業(yè)務(wù)QQ:195006118
技術(shù)QQ:179981967