我正在尝试找出连接池的最佳结构,以便我可以从任何 servlet 访问连接池并建立与我的数据库的连接。我一直在关注一些教程来设置和配置数据源和连接池,它们都在扩展 HttpServlet 的类中初始化和访问它们。所以它看起来像这样:
public class DatabaseConnector extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource dataSource;
private Connection connection;
private Statement statement;
public void init() throws ServletException {
try {
// Get DataSource
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/test");
} catch (NamingException e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#HttpServlet()
*/
public DatabaseConnector() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ResultSet resultSet = null;
try {
// Get Connection and Statement
connection = dataSource.getConnection();
statement = connection.createStatement();
String query = "SELECT * FROM STUDENT";
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + resultSet.getString(2) + resultSet.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (resultSet != null) {resultSet.close();}
if (statement != null) {statement.close();}
if (connection != null) {connection.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
在我看来,此连接池仅适用于此 servlet,它仅在向此 servlet URL 发送获取请求时才分发连接。如果我想要另一个需要访问数据库的 servlet 怎么办。我正在考虑仅删除此 servlet 中的 doGet 和 doPost 方法并保留 init 以便在运行时初始化连接池,然后对该 servlet 有一个可用于其他 servlet 的单例引用。但是,这对我来说似乎不是正确的方法。构建可以从所有 servlet 和侦听器访问的连接池的最佳方法是什么?
谢谢你的帮助!