【问题标题】:Java web application DAO writing authenticated UserID and IP Address to DBJava Web 应用程序 DAO 将经过身份验证的用户 ID 和 IP 地址写入数据库
【发布时间】:2010-07-22 20:46:08
【问题描述】:

每当我执行 SQL UPDATE 和 INSERT 时,我想将登录用户(Web 应用程序)的用户 ID 和 IP 地址写入我的 Oracle DB。比如

public static int updateUser(STKUser user, STKUser loggedIn) throws DAOException {
  Connection connection = null;
  connection = DB.getConnFromCache();

  PreparedStatement ps = null;

String query = "INSERT INTO xtblPersonnel (pID, pPssWrd, pAdminDate, pAdminIP, pAdminBy) VALUES (?,?,SYSDATE,?,?)";
  try {
    ps = connection.prepareStatement(query);
    ps.setString(1, user.getBadge());
    ps.setString(2, user.getPassword());
    ps.setString(3, loggedIn.getIpAddress());
    ps.setString(4, loggedIn.getBadge());
    return ps.executeUpdate();
  }
  catch (Exception e) {
     System.out.println("SQL Exception inserting new user with badge: " + user.getBadge() + ". Error Message: " + e.getMessage());
     LOGGER.log(Level.INFO, "SQL Exception inserting new user with badge: " + user.getBadge() + ". Error Message: " + e.getMessage(), user);
     throw new DAOException("SQL Exception inserting new user!");
     // return 0;
  }

  finally {
     DB.closePreparedStatement(ps);
     DB.releaseConnToCache(connection);
  }

}

STKuser 是一个 Javabean

我的应用程序使用通用的 Oracle 数据库用户名和密码,这就是为什么我要记录谁进行了更新或插入以及来自哪台机器的原因。

这是一种可接受的方法吗?我曾经参加过会议,但意识到这是不行的。

【问题讨论】:

  • 很难从给定的信息中分辨出来。为什么是 2 个 STKUser 对象?我猜他们似乎代表同一个用户。你在哪里初始化 PreparedStatement 和 Connection?捕获块在哪里?为什么这个方法声明为静态的?
  • 一个 STKUser 对象表示要添加到数据库的员工数据,第二个 STKUser 对象表示登录执行 SQL INSERT 的管理员。我已经编辑了答案以包含更多代码

标签: java jdbc dao


【解决方案1】:

假设您在获得它们的try 块的finally 块中正确关闭了所有数据库资源,如ConnectionStatementResultSet,并且代码正在执行它应该执行的操作,我不预见有问题的方法存在问题。由于您使用的是PreparedStatement,因此没有 SQL 注入风险,如果这是您真正关心的问题。然而,声明方法static 有点异味,但是我们需要更多地了解代码运行的上下文。

【讨论】:

  • 静态,因为方法只是 CRUD。但我仍在学习 J2EE。我这样称呼它,eclipse 促使我将其更改为 staic。如果表单上的一切都很好,那么我会调用:STKUserDAO.insert(formUser, loggedInUser);
猜你喜欢
  • 2012-06-20
  • 2017-11-11
  • 2017-11-15
  • 2013-02-16
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
相关资源
最近更新 更多