开发者

Need suggestion on how to work with connection polling in 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).

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

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>

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:

  • Basic DAO tutorial
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜