tomat database realm源码解析
protected synchronized String getPassword(String username) {
// Look up the user's credentials
String dbCredentials = null;
PreparedStatement stmt = null;
ResultSet rs = null;
// Number of tries is the number of attempts to connect to the database
// during this login attempt (if we need to open the database)
// This needs rewritten with better pooling support, the existing code
// needs signature changes since the Prepared statements needs cached
// with the connections.
// The code below will try twice if there is a SQLException so the
// connection may try to be opened again. On normal conditions (including
// invalid login - the above is only used once.
int numberOfTries = 2;
while (numberOfTries > 0) {
try {
// Ensure that we have an open database connection
open();
stmt = credentials(dbConnection, username);
rs = stmt.executeQuery();
if (rs.next()) {
dbCredentials = rs.getString(1);
}
dbConnection.commit();
if (dbCredentials != null) {
dbCredentials = dbCredentials.trim();
}
return dbCredentials;
} catch (SQLException e) {
// Log the problem for posterity
containerLog.error(sm.getString("jdbcRealm.exception"), e);
} finally {
if (rs != null) {
try {
rs.close();
} catch(SQLException e) {
containerLog.warn(sm.getString(
"jdbcRealm.abnormalCloseResultSet"));
}
}
}
// Close the connection so that it gets reopened next time
if (dbConnection != null) {
close(dbConnection);
}
numberOfTries--;
}
return (null);
}
在获取数据库连接的过程中,可能会有异常发生,tomcat realm机制中采用一个while循环,当有一场发生时,则会再一次尝试进行连接,该方法有待改进,可以采用数据库连接池来进行优化

浙公网安备 33010602011771号