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

21.6. Using a DataSource from WebLogic in a JSP

Problem

You want to use the javax.sql.DataSource that you set up on WebLogic in a JSP.

Solution

Use JSP scriptlets to access the DataSource with a JNDI lookup, then use the JDBC API in the scriptlets to access the database.

Discussion

The JSP in Example 21-6 transplants code from a servlet inside of HTML template text. The JSP uses scriptlets , which contain Java code within "<% %>" characters.

Tip

JSTL SQL tags are preferable to scriptlets in a JSP; however, the JSTL implementation I use for this book's examples cannot access a DataSource from WebLogic's JNDI implementation. See Recipe 23.6 for an example that uses the JSTL SQL tags with a Tomcat DataSource.

Example 21-6 imports the necessary classes at the top of the code using the page directive and its import attribute. Otherwise, this JSP accomplishes everything that the servlet of the prior recipe does, including the display of nearly identical output in the web browser (see Figure 21-1 in Recipe 21.1).

Example 21-6. Using a JSP scriptlet to access a WebLogic DataSource

<%@ page import="java.util.Hashtable,java.sql.*,javax.naming.*,javax.sql.*" %>

<html>
<head><title>Database Query in WebLogic</title></head>
<body>
<h2>Querying a database with a JSP in WebLogic</h2>

<%
    Context env = null; DataSource pool = null; Hashtable ht = new Hashtable( ); ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); ht.put(Context.PROVIDER_URL,"t3://localhost:7001"); env ...

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