[ Team LiB ] Previous Section Next Section

Recipe 23.8 Using A SQL JSTL Tag Without a DataSource Configuration


You want to specify the DataSource for the JSTL SQL tags inside a JSP.


Use the sql:setDataSource tag to establish a DataSource for the other SQL tags, such as sql:query.


You can explicitly set the DataSource for the JSTL SQL tags in a JSP using sql:setDataSource and its dataSource attribute. Example 23-9 creates the same DataSource as Recipe 23.6 and stores it in a variable named dSource. The sql:query tag then specifies this DataSource with its own dataSource attribute. The code otherwise accomplishes the same task as Example 23-8: the JSP sends a SELECT SQL statement to the database system, then displays the results.

Example 23-9. Using the sql:setDataSource tag
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql" %>

<head><title>Database Query</title></head>
<h2>Querying a database from a JSTL tag</h2>

<sql:setDataSource dataSource=
var="dSource" scope="application"/>

<sql:query var="athletes" dataSource="dSource">
SELECT * FROM athlete

<table border="1">

<c:forEach var="row" items="${athletes.rows}">


<td><c:out value="${row.user_id}"/></td>
<td><c:out value="${row.name}"/></td>
<td><c:out value="${row.birthdate}"/></td>
<td><c:out value="${row.passwrd}"/></td>
<td><c:out value="${row.gender}"/></td>



The code stores the DataSource in an application-scoped variable, so that another JSP can access the DataSource this way:

<sql:query var="athletes" dataSource="${dSource}">
SELECT * FROM athlete

The only difference between this sql:query usage and Example 23-9 is that the value of the dataSource attribute has to be resolved using the EL; the tag has to find and get the value of an application-scoped variable (a servlet context attribute) named "dSource."

You can also specify a DataSource in the JSTL SQL tags as a Java Naming and Directory Interface (JNDI) string, but we will reserve discussion of that topic for Chapter 21, which covers using databases with servlets and JSPs.

See Also

Chapter 21 on working with databases; the Jakarta Project's Taglibs site: http://jakarta.apache.org/taglibs/index.html; the Sun Microsystems JSTL information page: http://java.sun.com/products/jsp/jstl/; Recipe 23.3 on using the core tags; Recipe 23.4 and Recipe 23.5 on using the XML tags; Recipe 23.6 on using the formatting tags; Recipe 23.7 and Recipe 23.8 on using the SQL JSTL tags; Recipe 23.9-Recipe 23.14 on using the EL to access scoped variables, cookies, and JavaBean properties.

    [ Team LiB ] Previous Section Next Section