Where should I setup a Database connection in Struts 2 app?
I am developing a small web application using struts 2. I want to setup a database connection when the web application starts. After that, I want that database connection object to be used in the the entire web application to upd开发者_JAVA百科ate records in the database server.
Where should I include the database connection setup code in my struts2 web application ?
You shouldn't setup a database connection on webapp startup. The DB will timeout the connection when it is been released for a too long time and that is truly shorter (~30 mins) than the time an average webapplication lives (days, months, years). Rather setup the datasource / DAO factory at that point. Connections are to be acquired and closed in the shortest possible scope. The normal JDBC idiom is the following:
public void create(Entity entity) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL_CREATE);
statement.setSomeObject(1, entity.getSomeProperty());
// ...
statement.executeUpdate();
} finally {
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
}
Note the closing in finally
. It prevents leaking resources (i.e. not closing them) when an exception occurs.
To improve connecting performance you normally want to use a connection pool. Any decent appserver provides this facility in flavor of a JNDI datasource. In for example Tomcat, you can find in the JNDI Resources HOW-TO how to create one. This by the way does not mean that you don't need to close them, you still need to close them according the usual JDBC idiom. The connection pool namely returns a wrapped connection which does something like the following in the close()
:
public void close() throws SQLException {
if (this.connection is still eligible for reuse) {
do not close this.connection, but just return it to pool for reuse;
} else {
actually invoke this.connection.close();
}
}
As to setting up the datasource (or DAO factory) on webapp startup, there are several ways. One is using a ServletContextListener
which does the task in the contextInitialized()
method, another way is using a Struts2-managed application scoped bean which does the task in the constructor.
Also see this basic JDBC/DAO tutorial for more hints how to get started with JDBC (in webapplications) the proper way.
精彩评论