How to configure Postgres DataSource in Tomcat 7

Step1:download postgres jdbc jar file place in lib folder



Step2: create one context.xml file inside META-INF


context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<Context>

  <Resource name="jdbc/database" auth="Container" type="javax.sql.DataSource"
               maxActive="50" maxIdle="30" maxWait="10000"
               username="postgres" password="password"
               driverClassName="org.postgresql.Driver"
               url="jdbc:postgresql://192.168.0.119/databasename"/>

</Context>

In web.xml  add resource ref

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

  </resource-ref>

Access In class while running tomcat

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public static  void  check()
{
     DataSource ds=null;

   
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/database");
 Connection con = ds.getConnection();
 System.out.println(con);
 } catch (Exception e) {
e.printStackTrace();
 }
}

Comments