Search code examples
jspjstldatasourceweb.xml

Using web.xml to get JSTL sql dataSource?


Attempting to get a dataSource for JSTL SQL operations, and it won't connect.

In my web.xml:

<context-param>
    <param-name>databaseJNDI</param-name>
    <param-value>jdbc/testDS</param-value>
</context-param>

What I'm attempting in my JSP file:

<sql:setDataSource dataSource = "jdbc/testDS"/>

I'm attempting to do this and failing in order to avoid hard-coding the database credentials into the page. The database is running, but I don't know enough about JSTL to tackle this on my own right now.

It is complaining about driver, but I have used the same design for servlets without specifying a driver to access the database.

Any insight into my issue? Knowing my luck it's probably something simple.


Solution

  • Using initParam you can get context parameters.

    Create context-params in web.xml for database connection properties:

    <context-param>
        <param-name>driverClass</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
    <context-param>
        <param-name>connectionURL</param-name>
        <param-value>jdbc:mysql://localhost/dbname</param-value>
    </context-param>
    <context-param>
        <param-name>username</param-name>
        <param-value>foo</param-value>
    </context-param>
    <context-param>
        <param-name>password</param-name>
        <param-value>bar</param-value>
    </context-param> 
    

    In JSP use

    <sql:setDataSource var="dataSource" 
       driver="${initParam['driverClass']}"
       url="${initParam['connectionURL']}" 
       user="${initParam['username']}"
       password="${initParam['password']}" />