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

标签 java database jsp jdbc database-connection

我有一堆 JSP 页面。

我有一个 Java 类,它在初始化时从连接池获取数据库连接。我稍后在 JSP 中使用该连接。

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

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

最佳答案

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

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

关于java - 如何创建 JSP 页面和共享数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31898243/

相关文章:

java - PermGen 空间异常

java - 从一个java类调用另一个类的方法时出现问题

java - 如何使用CDI进行方法参数注入(inject)?

java - 为什么我不能创建控制台类的对象?

node.js - 在 Node 中检查付款状态的有效方法?

用户存在时 PHP 登录脚本不起作用

python - Hadoop:在 Ubuntu 12.04 中通过 NameNode 格式化 HDFS 文件系统

java - 如何在 Struts 2 中为每个做

java - 修改同一个jsp文件的两个钩子(Hook)之间的冲突

java - 对于 sendredirect ,哪个方法被调用 doGet 或 doPost()