0

我在 tomcat 8 中有一个带有 servlets 技术的网络应用程序。对于数据库连接,我有一个 servlet 侦听器,它保留一个静态数据源和一个执行 getConnection 的静态方法。我可以调用 servletListener.getConnection(); 在 servletListener.getConnection();

但是内部类不能调用它。

我在网上找到了这门课:

public final class DBUtilClass {
    private static DataSource datasource;

    static {
        Context initContext;
        try {
            initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            datasource = (DataSource) envContext.lookup("jdbc/testdb");
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return datasource.getConnection();
    }

我喜欢它,因为我可以从所有课程中调用它。我不确定这是否是最好的方法。

其他人的做法?有什么推荐吗?

4

0 回答 0