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

JBuilder 2005 實戰 JSP:HttpSessionBindingListener 實作登入登出日誌與部署

     編輯:關於JSP

事件驅動日誌機制

實作 HttpSessionBindingListener,物件綁定/解除綁定 Session 時自動觸發:

  • valueBound():寫入登入日誌 (INSERT)。
  • valueUnbound():更新登出時間 (UPDATE)。

User.java 完整實作

public class User implements HttpSessionBindingListener {
    private String userId, loginDatetime;
    // ... getter/setter 略 ...

    public void valueBound(HttpSessionBindingEvent event) {
        Connection conn = null;
        try {
            conn = DBConnection.getConnection();
            PreparedStatement ps = conn.prepareStatement(
                "insert into T_LOGIN_LOG(ID, USER_ID, DT_LOGIN) values(SEQ_LOGIN_LOG_ID.NEXTVAL,?,?)");
            loginDatetime = getCurrDatetimeStr(); // yyyyMMddHHmmss
            ps.setString(1, userId);
            ps.setString(2, loginDatetime);
            ps.executeUpdate();
        } catch (SQLException e) { throw new RuntimeException("登入日誌寫入失敗", e); }
        finally { closeQuietly(conn); }
    }

    public void valueUnbound(HttpSessionBindingEvent event) {
        Connection conn = null;
        try {
            conn = DBConnection.getConnection();
            PreparedStatement ps = conn.prepareStatement(
                "update T_LOGIN_LOG set DT_LOGOUT=? where USER_ID=? and DT_LOGIN=?");
            ps.setString(1, getCurrDatetimeStr());
            ps.setString(2, userId);
            ps.setString(3, loginDatetime);
            ps.executeUpdate();
        } catch (SQLException e) { throw new RuntimeException("登出日誌寫入失敗", e); }
        finally { closeQuietly(conn); }
    }

    private static String getCurrDatetimeStr() {
        return new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date());
    }
}

流程串聯

  1. login.jsp 送表單 → switch.jsp 驗證通過。
  2. switch.jsp 執行 session.setAttribute("ses_userBean", userBean) → 觸發 valueBound() 寫入登入記錄。
  3. 導向 welcome.jsp。
  4. 用戶點「登出」 → quit.jsp 呼叫 session.invalidate() → 觸發 valueUnbound() 更新登出時間。

Web 容器其他事件介面

介面事件
ServletContextListenerWeb 應用啟動/銷毀
HttpSessionListenerSession 建立/銷毀
ServletRequestListenerRequest 建立/銷毀 (J2EE 1.4+)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved