It depends on the running environment. I assume that you're running a webapplication using an applicationserver, like Glassfish or Tomcat.
1) Configure a DataSource in the administration console of the server and give it an JNDI name.
2) In the Javacode retrieve the DataSource from JNDI.
3) Retrieve the connection from it.