需要建议如何使用连接轮询在java(jsp& servlet) [英] Need suggestion on how to work with connection polling in java(jsp&servlet)

查看:399
本文介绍了需要建议如何使用连接轮询在java(jsp& servlet)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的项目。在这个项目中,我使用n否的jsp页面和servlet与数据库进行交互。如何我必须写连接字符串。目前,我写了连接字符串每个和每个jsp页面(我知道这不是一个最佳实践)。现在我的问题是我如何管理连接字符串?我必须写在只有一个共同的页面,然后我必须利用..如何实现这个?

I'm developing a simple project.In this project i'm using n no of jsp pages and servlets to interact with the database. How i have to write the connection string. Presently i written the connection string each and every jsp page.(I knew this is not a best practice). Now my question is how i have to manage the connection string? I have to write in only one common page, then i have to utilize that.. How i can implement this ?? Could any one guide me on this??

推荐答案

您需要在servletcontainer中创建一个JNDI数据源。默认情况下,它是一个连接池数据源。如何做到这一点取决于servletcontainer make / version。所以这里只是一个Tomcat目标示例:

You need to create a JNDI datasource in the servletcontainer. It is by default a connection pooled datasource already. How to do that depends on the servletcontainer make/version. So here's just a Tomcat targeted example:

首先创建一个文件 /META-INF/context.xml 要清楚,META-INF与webapp的WEB-INF处于同一级别),并填写以下内容(假设有一个MySQL DB)。

First create a file /META-INF/context.xml (to be clear, the META-INF is at the same level as the WEB-INF of the webapp) and fill it with the following (assuming a MySQL DB).

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource
        name="jdbc/mydatabase" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000" 
        url="jdbc:mysql://localhost:3306/mydatabase"
        driverClassName="com.mysql.jdbc.Driver"
        username="java" password="pass"
    />
</Context>

然后注册到您的webapp的 /WEB-INF/web.xml

Then register it in your webapp's /WEB-INF/web.xml.

<resource-env-ref>
    <resource-env-ref-name>jdbc/mydatabase</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

在数据库管理器/ DAO类中获取如下。

Get it as follows in your DB manager / DAO class.

try {
    this.dataSource = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/mydatabase");
} catch (NamingException e) {
    throw new RuntimeException("DataSource is missing in JNDI.", e);
}



最后得到它在DAO方法中的连接,

Finally get the connection of it inside the DAO method where you're executing the query.

connection = dataSource.getConnection();

不要忘记 close()它在中的 finally 中找到

  • Basic DAO tutorial

这篇关于需要建议如何使用连接轮询在java(jsp&amp; servlet)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆