Q:

Proper way to register jdbc driver in Google app Engine app

I'm working on a project where we use GAE with Google Cloud SQL. I've followed this tutorial https://developers.google.com/appengine/docs/java/cloud-sql/developers-guide#use_with_lang to learn how to connect to the database and so far everything is fine except for the driver registration part. My intuition tells me that the driver should be registered only once but I don't know where and when is the best place to do it. Is there a kind of initialization feature in gae that can execute some code when an instance gets started? Or maybe a xml file that could load the resources?
So far my code looks like this:
    try {
        // Connect to the db.
        DriverManager.registerDriver(new AppEngineDriver());
        Connection c = DriverManager.getConnection(JDBC_CON_STRING);

        // Fetch rows
        String sql = "SELECT * FROM test";
        ResultSet rs = c.createStatement().executeQuery(sql);
        ArrayList<BaseUser> users = new ArrayList<BaseUser>();
        while(rs.next()){
            BaseUser u = new BaseUser();
            u.setFirstname(rs.getString("firstname"));
            u.setLastname(rs.getString("lastname"));
            users.add(u);
        }
        rs.close();
        c.close();
        // Print the users in the console.
        for (BaseUser user : users) {
            logger.info("Firstname: " + user.getFirstname() + ", Lastname: " + user.getLastname());
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

I want to get rid of the first line and put it somewhere where it will get executed only once and then, each time I receive a request that needs sql transactions I'll just have to call DriverManager.getConnection(...)
Thank you,
Rodrigo.

A:

So I finally found, in google's doc, a better way to "run custom logic before any of the servlets is invoked". Here it's: Simply register a ServletContextListener in web.xml and override the contextInitialized method, in my case, the custom driver registration.
Here's the web.xml code:
<web-app>
    ...
   <welcome-file-list>
       <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <listener>
       <listener-class>com.my.project.ClassName</listener-class>
   </listener>
</web-app>

And the contextInitializeMethod:
@Override
public void contextInitialized(ServletContextEvent arg) {
    try {
        DriverManager.registerDriver(new AppEngineDriver());
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Here's the link to the actual google guide: https://developers.google.com/appengine/docs/java/config/appconfig#Using_a_ServletContextListener
Hope it help's anyone with a similar issue.

