gpt4 book ai didi

mysql - 传递 jdbc 数据源与传递 Connection 对象 - 从 servlet 到 java 类

转载 作者:行者123 更新时间:2023-11-29 02:04:28 25 4
gpt4 key购买 nike

我有一个处理 post/get 请求的主 Servlet。
我正在使用连接池(带有 glassfish v3 的 jdbc/mysql),我的 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);
}

等等... 并在 servlet 末尾的 finally block 中关闭连接

所以现在我在最后一行将“连接”对象作为参数传递,以供其他(非 servlet)java 类通过应用程序的较低层使用。这是错误的吗?传递数据源对象(然后在特定类中执行 datasource.getConnection())是否更好?或者是否有类似于 "getServletContext().getAttr(database)" 的东西可以在其他 java 类中使用以获取此连接?

最佳答案

DataSource 允许获取 JDBC 连接(大部分时间来自连接池)。在 servlet 环境中,如果您两次请求与 DataSource 的连接,您将获得两个不同的连接。

因此传递 DataSource 没有意义:您希望调用链中的所有对象使用相同的连接,并在最后提交。

并且必须通过从 DataSource 获取连接的方法在 finally block 中关闭连接,否则连接池将泄漏连接,您将很快耗尽可用连接。

关于mysql - 传递 jdbc 数据源与传递 Connection 对象 - 从 servlet 到 java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8957501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com