首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Servlet HttpSessionBindingListener 與 HttpSessionBindingEvent 完整解析

     編輯:關於C++

HttpSessionBindingListener

接口定義:當對象被綁定到 Session 或從 Session 解綁時,容器自動回調。

public interface HttpSessionBindingListener {
    void valueBound(HttpSessionBindingEvent event);   // 綁定時調用
    void valueUnbound(HttpSessionBindingEvent event); // 解綁時調用
}

觸發時機:session.setAttribute(name, obj) → valueBound;session.removeAttribute(name) 或 Session 失效 → valueUnbound。

用途:對象感知自身生命周期,如釋放資源、記錄日誌、更新緩存計數。

HttpSessionBindingEvent

事件對象,封裝 Session、屬性名、屬性值。

public class HttpSessionBindingEvent extends HttpSessionEvent {
    private String name;
    private Object value;
    public HttpSessionBindingEvent(HttpSession session, String name) { ... }
    public HttpSessionBindingEvent(HttpSession session, String name, Object value) { ... }
    public String getName() { return name; }
    public Object getValue() { return value; }
    public HttpSession getSession() { return super.getSession(); }
}

實戰示例:在線用戶計數器

public class OnlineUser implements HttpSessionBindingListener {
    private String username;
    public OnlineUser(String u) { username = u; }
    public void valueBound(HttpSessionBindingEvent e) {
        ServletContext ctx = e.getSession().getServletContext();
        Integer cnt = (Integer) ctx.getAttribute("online");
        ctx.setAttribute("online", (cnt==null?1:cnt+1));
        System.out.println(username + " 上線,當前 " + (cnt==null?1:cnt+1));
    }
    public void valueUnbound(HttpSessionBindingEvent e) {
        ServletContext ctx = e.getSession().getServletContext();
        Integer cnt = (Integer) ctx.getAttribute("online");
        ctx.setAttribute("online", Math.max(0, (cnt==null?0:cnt-1)));
        System.out.println(username + " 下線");
    }
}

// 登入時
session.setAttribute("user", new OnlineUser("alice")); // 觸發 valueBound
// 登出/超時時
session.removeAttribute("user"); // 或 session.invalidate() 觸發 valueUnbound

關鍵點總結

注意事項

  1. 實現該接口的類**無需在 web.xml 註冊**,容器自動檢測屬性值實例。
  2. valueUnbound 在 Session 超時銷毀時也會調用(非僅手動 remove)。
  3. 區別 HttpSessionAttributeListener:後者是全局監聽器(需註冊),前者是屬性值對象自身感知。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
接口/類核心方法觸發條件
HttpSessionBindingListenervalueBound / valueUnboundsetAttribute / removeAttribute / invalidate
HttpSessionBindingEventgetName / getValue / getSession作為回調參數傳遞