首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> Oracle 資料庫 >> Oracle 資料庫基礎

JSP 中呼叫 Bean 並透過 Bean 呼叫 Oracle 預存程序

     編輯:Oracle 資料庫基礎

需求背景

建立一個登入系統,需達成:

  1. 使用者透過 Bean 進行驗證並取得使用者資訊。
  2. 記錄使用者登入資訊,如登入次數、最後登入時間。
  3. 記錄操作日誌。

未解決問題

  • 使用者登入後的 Session 是否可透過 Bean 判斷。
  • 透過 Bean 呼叫 Oracle 預存程序,回傳 SELECT 的記錄集。

實作步驟

1. 建立使用者驗證 Bean

public boolean checkUser() throws Exception {
  boolean flag = false;
  ResultSet rs = conn.executeQuery(getSql());
  if (rs.next()) {
    userID = rs.getString("userID");
    userName = rs.getString("userName");
    userPWD = rs.getString("userPWD");
    userUnit = rs.getString("userUnit");
    userLoadTime = rs.getDate("userLoadTime");
    userLoadNumeric = rs.getInt("userLoadNumber");
    flag = true;
  }
  rs.close();
  conn.closeConn();
  return flag;
}

透過回傳值判定使用者是否存在。

2. 記錄使用者登入資訊

public void changeLoginInfo(String userID) throws Exception {
  String sql = "UPDATE SystemUserTable SET UserLoadTime=sysdate, " +
               "UserLoadNumber=UserLoadNumber+1 WHERE userID='" + userID + "'";
  conn.executeUpdate(sql);
}

3. 記錄操作日誌

步驟一:建立預存程序

CREATE OR REPLACE PROCEDURE proc_writeNote(
  description IN VARCHAR2,
  wName IN VARCHAR2,
  wIP IN VARCHAR2
) IS
BEGIN
  INSERT INTO Systemnote (Id, Description, Wname, Wip) 
  VALUES (Autoaddid.Nextval, description, wName, wIP);
  COMMIT;
END proc_writeNote;

步驟二:建立操作預存程序的方法(重寫 prepareCall)

public CallableStatement prepareCall(String produce) {
  try {
    conn = DriverManager.getConnection(DBUrl, UserID, UserPWD);
    cstmt = conn.prepareCall(produce);
  } catch (SQLException ex) {
    System.err.print("prepareCall():" + ex.getMessage());
  }
  return cstmt;
}

步驟三:執行預存程序

public void writeNote(String description, String wName, String wIP) {
  String sql = "{call proc_writeNote(?,?,?)}";
  try {
    CallableStatement cstmt = conn.prepareCall(sql);
    cstmt.setString(1, description);
    cstmt.setString(2, wName);
    cstmt.setString(3, wIP);
    cstmt.executeUpdate();
  } catch (SQLException ex) {
    System.out.print("writeNote():" + ex.getMessage());
  }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved