1

I have installed PostgreSQL 9.5.2 (rhel 6.7 x64) and Apache Tomcat 7.0.73(x64 rhel 6.7) after this i have downloaded postgresql-9.4.1212.jar jar file and paste to Catalina_home/Lib path and adding this following to content.xml file

<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"/>

Adding Following to web.xml file

<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>

So how can i test that Apache Tomcat Server is connected to PostgreSQL database server?

1 Answer 1

1

Tomcat has given a guide of JNDI Datasource HOW-TO, specifically:

  1. Accessing the datasource

    When accessing the datasource programmatically, remember to prepend java:/comp/env to your JNDI lookup, as in the following snippet of code. Note also that "jdbc/postgres" can be replaced with any value you prefer, provided you change it in the above resource definition file as well.

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!");
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Jacek Cz yeah, you need to try and catch the block of code, because InitialContext and cxt.lookup explicitly throw certain types of exceptions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.