如何创建 JSP 页面和共享数据库连接

How to create JSP pages and Shared DB connection

我有一堆 JSP 页。

我有一个 Java class,它在初始化时从连接池获取数据库连接。我稍后在 JSP.

中使用该连接

是否可以有一个父 JSP 页面,我可以在其中 define/get 连接并在我的所有 JSP 页面上使用它,然后在用户点击注销时关闭连接?

或者请建议执行此操作的最佳方法是什么?

创建数据源并使用 JNDI 将其发布到服务器上。稍后在 JSP 中,您可以使用此资源引用来执行对数据库的查询。您还可以从此数据源获取连接对象,但不应在用户之间共享此连接。在通过关闭连接完成查询后,您应该 return 连接到池。

The most efficient way to implement communication between the server and database is to set up a database connection pool. Creating a new connection for each client request can be very time-consuming, especially for applications that continuously receive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool. Any incoming requests that require access to the application's data layer use an already-created connection from the pool. Likewise, when a request is completed, the connection is not closed down, but returned to the pool.

After preparing the data source and connection pool for the server, you then need to instruct the application to use the data source. This is typically done by creating an entry in the application's web.xml deployment descriptor. Finally, you need to ensure that the database driver (MySQL Connector/J JDBC Driver) is accessible to the server.

参考文献:Creating a Simple Web Application Using a MySQL Database