Apache Tomcat 连接到 PostgreSQL 数据库(通过 JDBC 驱动程序)

问题描述 投票:0回答:1

我已经安装了 PostgreSQL 9.5.2 (rhel 6.7 x64) 和 Apache Tomcat 7.0.73(x64 rhel 6.7) 之后我下载了 postgresql-9.4.1212.jar 文件并粘贴到 Catalina_home/Lib 路径并将以下内容添加到content.xml 文件

<Resource auth="Container" name="jdbc/postgres" type="javax.sql.DataSource" user="sarkhan" password="1"
            driverClassName="org.postgresql.Driver" url="jdbc:postgresql://172.29.92.162:5432" maxActive="150"
            schema="test" maxIdle="4"/>

将以下内容添加到 web.xml 文件

<resource-ref>
    <description>postgreSQL Datasource</description>
    <res-ref-name>jdbc/postgres</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

那么我如何测试 Apache Tomcat 服务器是否已连接到 PostgreSQL 数据库服务器?

postgresql tomcat tomcat7 postgresql-9.3
1个回答
0
投票

Tomcat 给出了 JNDI Datasource HOW-TO 的指南,具体为:

  1. 访问数据源

    以编程方式访问数据源时,请记住将 java:/comp/env 添加到 JNDI 查找中,如以下代码片段所示。另请注意,“jdbc/postgres”可以替换为您喜欢的任何值,前提是您也在上面的资源定义文件中更改它。

InitialContext cxt = new InitialContext();
if ( cxt == null ) {
   throw new Exception("Uh oh -- no context!");
}

DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );

if ( ds == null ) {
   throw new Exception("Data source not found!");
}
© www.soinside.com 2019 - 2024. All rights reserved.