O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

23.8. Using A SQL JSTL Tag Without a DataSource Configuration

Problem

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

Solution

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

Discussion

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" %>

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

<sql:setDataSource dataSource=
"jdbc:oracle:thin:@192.168.0.2:1521:ORCL,oracle.jdbc.driver.OracleDriver,scott,tiger" 
var="dSource" scope="application"/>

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

<table border="1">

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

<tr>
<th>user_id</th>
<th>name</th>
<th>birthdate</th>
<th>passwrd</th>
<th>gender</th></tr>

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required