views:

382

answers:

2

Hiya.

I would like to store db connection information in the application web.xml file and to fetch it in the application. i read somewhere that it's possible i just don't know how.

any ideas?

thanks!

+1  A: 

You add them as a context-param to your web.xml:

<context-param>
    <description>My variable</description>
    <param-name>variable.name</param-name>
    <param-value>value</param-value>
</context-param>

Then within your servlet, you call getInitParameter() on your ServletContext:

String variable = getServletContext().getInitParameter("variable.name");
Kaleb Brasee
+2  A: 

1) Depending on your Application server or Container-Managed server, CREATE a Connection Pool.

2) Link your resource pool in your web.xml

e.g. (Tomcat 5.5 and higher).

I have an Example_DS (Datasource) in my connection pool, and here I share it in my web.xml

<resource-ref>
        <description>Database Connection for Example</description>
        <res-ref-name>jdbc/Example_DS</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>

This matches my resource created on context.xml (found in META-INF folder) on my web application. Still using Tomcat.

<Resource name="jdbc/Example_DS" auth="Container" type="javax.sql.DataSource"
            maxActive="100" maxIdle="30" maxWait="10000"
            username="YOURUSERNAMEHERE" password="YOURPASSWORDHERE" driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/DATABASEHERE?autoReconnect=true" 
            removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"
            testOnBorrow="true" validationQuery="SELECT 1" />

Clearly, you can see I'm using MySQL here.

<Resource /> allows you to create a connection pool (in Tomcat)

In JBoss....

1) Create a Example_DS.xml file where Example is the name of your datasource.

E.g.

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
   <local-tx-datasource>
      <jndi-name>Example_DS</jndi-name>
      <connection-url>jdbc:mysql://localhost:3306/DATABASEHERE?autoReconnect=true</connection-url>
      <driver-class>com.mysql.jdbc.Driver</driver-class>
      <user-name>YOURUSERNAMEHERE</user-name>
      <password>YOURPASSWORDHERE</password>
      <min-pool-size>0</min-pool-size>
      <max-pool-size>100</max-pool-size>
      <idle-timeout-minutes>2</idle-timeout-minutes>
      <track-statements>false</track-statements>
   </local-tx-datasource>
</datasources>

Then user the <resource-ref> that I gave up earlier to map it to your DS in Jboss. Deploy your DS.xml file in /server/default/deploy/ folder and restart JBoss.

Once you're done, then you can call it in Java using Context.

The Elite Gentleman
I hope it's what you're looking for else I'm sorry for writing long essays here....For those, in future, bookmark this. LOL.
The Elite Gentleman