Hi Magnus.
The standard "enterprisey" way to do this, would be to use a
javax.sql.DataSource as a representation of your database. Your
RemoteServiceServlet would look up this object in JNDI at
initialization time, and create connections by calling
"getConnection()" on it each time a user connect.
The actual connection pool would be managed outside your application.
For example, when you define a DataSource resource in Tomcat, an
Apache connection pool (DBCP) is created. This way, when your
application asks for a new connection, it will be transparently
reusing pooled connections.
Example servlet:
class MyServlet
extends RemoteServiceServlet
implements MyServletService
{
@Resource(name="jdbc/db") // This makes your servlet container
inject the JNDI resource found under jdbc/db
private DataSource db;
public void myGwtMethod() {
Connection conn = db.getConnection();
}
...
}
If you're using Tomcat, take a look here for how to manage DataSource
resources:
http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html.
To answer your specific question, if you want code to run once at init-
time, override init(). If you want code to run once at shutdown time,
override destroy(). But you shouldn't need these, since the @Resource
annotation will cause the container to do the initialization for you.
... and don't forget to close() your connections, even if exceptions
were raised, otherwise you'll have a leak.
Shay