【发布时间】:2012-02-15 23:14:23
【问题描述】:
我有一个处理 post/get 请求的主 Servlet。
我正在使用连接池(jdbc / mysql 和 glassfish v3),我的 servlet 代码是:
public class Controller extends HttpServlet {
private DataSource datasource;
@Override
public void init() throws ServletException {
super.init();
try {
//Database Connection pooling:
InitialContext ctx = new InitialContext();
datasource = (DataSource)ctx.lookup("jdbc/MySQLPool");
}
catch (Exception e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return datasource.getConnection();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection connection=null;
try {
connection = datasource.getConnection();
Object obj= cmdFactory.getInstance().getCommand(Cmd).execute(connection);
}
etc... 并在 servlet 的最后一个 finally 块中关闭连接
所以现在我将“连接”对象作为最后一行中的参数传递,以供其他(非 servlet)java 类通过应用程序的较低层使用。这是错的吗?传递数据源对象是否更好(然后在特定类中执行 datasource.getConnection())?或者是否有类似于 "getServletContext().getAttr(database)" 的东西可以在其他 java 类中用于获取此连接?
【问题讨论】:
标签: mysql jakarta-ee servlets jdbc connection-pooling