接口定義:當對象被綁定到 Session 或從 Session 解綁時,容器自動回調。
public interface HttpSessionBindingListener {
void valueBound(HttpSessionBindingEvent event); // 綁定時調用
void valueUnbound(HttpSessionBindingEvent event); // 解綁時調用
}
觸發時機:session.setAttribute(name, obj) → valueBound;session.removeAttribute(name) 或 Session 失效 → valueUnbound。
用途:對象感知自身生命周期,如釋放資源、記錄日誌、更新緩存計數。
事件對象,封裝 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
| 接口/類 | 核心方法 | 觸發條件 |
|---|---|---|
| HttpSessionBindingListener | valueBound / valueUnbound | setAttribute / removeAttribute / invalidate |
| HttpSessionBindingEvent | getName / getValue / getSession | 作為回調參數傳遞 |