我已经安装了 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 数据库服务器?
Tomcat 给出了 JNDI Datasource HOW-TO 的指南,具体为:
访问数据源
以编程方式访问数据源时,请记住将 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!");
}