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.9. Converting a ResultSet to a Result Object

Problem

You want to convert a java.sql.ResultSet to a javax.servlet.jsp.jstl.sql.Result object so that the object can be used with the JSTL.

Solution

Use the javax.servlet.jsp.jstl.sql.ResultSupport.toResult( ) method.

Discussion

The Result interface allows code to work with ResultSets in the form of Java arrays or java.util.Maps. The JSTL tags often use arrays or Maps to iterate through values (which is why they included the Result interface in the JSTL specification). Therefore, you might want to convert a ResultSet to a Result, then hand the Result to a JSP that uses the JSTL tags.

Example 21-12 is a servlet that:

  1. Creates a ResultSet by querying a database.

  2. Converts the ResultSet to a Result.

  3. Forwards the Result to a JSP by storing the Result as a session attribute.

Example 21-12. A servlet converts a ResultSet to a Result

package com.jspservletcookbook;import java.sql.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.*;

import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport; import javax.servlet.*; import javax.servlet.http.*; public class DbServletResult extends HttpServlet { DataSource pool; public void init( ) throws ServletException { Context env = null; try{ env = (Context) new InitialContext( ).lookup("java:comp/env"); pool = (DataSource) env.lookup("jdbc/oracle-8i-athletes"); if (pool == null) throw new ServletException( ...

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