Getting started

If you'd like to try the tutorial without screwing up your own computer, I'd suggest to start two virtual private servers on DigitalOcean. The smallest instance currently costs $5 a month (or less than 20c for a day) and has more than enough power for our purposes. If you use this link, you get a $10 credit.
We will be using Ubuntu 14.04 64bit.

Now we have to enable remote access to the PostgreSQL Server.
We open the pg_hba.conf file:sudo su - postgres
vi /etc/postgresql/9.3/main/pg_hba.conf

Now add following line to this file (this allows access for all users with a valid password for all created databases):host all all all md5

Save and exit. The PostgreSQL server is configured to only accept connections from the localhost, we have to change this in the postgresql.conf file:vi /etc/postgresql/9.3/main/postgresql.conf

Change this line as follows:listen_addresses='*'

Save and exit. Restart PostgreSQL:sudo service postgresql restart

You're done. You can try to connect to your database server as follows (xxx is your IP adress):psql -h xxx -U postgres_user exampledb
The server will then ask you for your password to connect. If this doesn't work be sure that your firewall has port 5432 open.

Write your Servlet

We will use a small servlet to check the functionality and show how to use connection pooling.
A connection pool is a group of several connections, which the Server (in our case Tomcat) manages. The advantage is that not every process from our servlet will be creating a new connection, but the connections are kept open, thus increasing performance.
The setup is quite straightforward, and we will be focusing only on the differences to a normal servlet.
context.xml
If it doesn't exist yet, create a context.xml in the META-INF folder. The context stores all details about the connection, including username and password:

The DataSource is created in the line
ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/postgres");
which looks it up from our web.xml (which in turn reads context.xml).
The connection is then created from the DataSource:
Connection connection = ds.getConnection();
The connection can then be used as always.
Compile your servlet into a War-file.

Setting up the application server

Before you start the webserver, the current PostgreSQL JDBC driver has to be added to Tomcat's lib folder.
The driver can be found here: http://jdbc.postgresql.org/
Download it into following folder: /usr/share/tomcat7/lib

Tomcat can now be started as follows:sudo service tomcat7 start

After starting Tomcat you can see your servlet under http://localhost:8080/projectName/postgresServlet. If everything works okay, you should see the database entries (the second column) listed in the output.