jsp是怎么连接java,需要建议如何使用连接轮询在java(jsp& servlet)

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??

解决方案

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:

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).

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"

/>

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

jdbc/mydatabase

javax.sql.DataSource

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);

}

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

connection = dataSource.getConnection();

Don't forget to close() it inside the finally of the try where you're getting it.

See also:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值