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循环,当有一场发生时,则会再一次尝试进行连接,该方法有待改进,可以采用数据库连接池来进行优化

posted @ 2015-10-12 16:28  程序猿进化之路  阅读(175)  评论(0)    收藏  举报