C.3 SQLJ in JavaServer Pages
JavaServer Page s (JSP) are similar to HTML pages except that they contain Java statements in addition to the HTML tags. This section shows a simple JSP, named JSPExample.sqljsp, that contains SQLJ statements, and then describes how to deploy that JSP to iAS. For an introduction to JavaServer Pages, I recommend the book JavaServer Pages by Hans Bergsten (O'Reilly).
A JSP file normally has the extension .jsp. However, a JSP that contains SQLJ statements must have the extension .sqljsp. This extension tells iAS that before running the JSP, it must first use the SQLJ utility to translate any SQLJ statements that may be in the file. The example program, JSPExample.sqljsp (Example C-3), retrieves and displays the same customer details as the other examples in this appendix.
Example C-3. JSPExample.sqljsp
<!-- JSPExample.sqljsp illustrates how to include SQLJ statements in JavaServer Pages. --> <!-- Import the SQLJ classes --> <%@ page import="java.sql.*" %> <%@ page import="sqlj.runtime.ref.DefaultContext,oracle.sqlj.runtime.Oracle" %> <html> <head> <title>Customers</title> </head> <body> <%! // declare an iterator class #sql private static iterator CustIteratorClass( int id, String first_name, String last_name, java.sql.Date dob, String phone ); %> <% try { DefaultContext conn_context = Oracle.connect( "jdbc:oracle:thin:@localhost:1521:orcl", "fundamental_user", "fundamental_password" ); CustIteratorClass cust_iterator; #sql [conn_context] cust_iterator = { SELECT id, first_name, last_name, dob, phone FROM customers }; %> <table width=100% border=1> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>DOB</th> <th>Phone</th> </tr> <% while (cust_iterator.next( )) { %> <tr> <td><%= cust_iterator.id( ) %> </td> <td><%= cust_iterator.first_name( ) %></td> <td><%= cust_iterator.last_name( ) %> </td> <td><%= cust_iterator.dob( ) %> </td> <td><%= cust_iterator.phone( ) %> </td> </tr> <% } // end of while %> </table> <% cust_iterator.close( ); conn_context.close( ); } catch (SQLException e) { %> SQLException <%= e %> <% } %> </body> </html>
You don't have to translate or compile JSPExample.sqljsp prior to deployment because when the JSP is invoked, the iAS does the translation and compilation for you. You can deploy JSPExample.sqljsp to the iAS by copying the file to the directory ORACLE_HOME\Apache\Apache\htdocs\demo\sql\sqlj (ORACLE_HOME is the directory in which iAS is installed). You can then invoke JSPExample.sqljsp by pointing your browser to the following URL:
- http://localhost/demo/sql/sqlj/JSPExample.sqljsp
The output from JSPExample.sqljsp, as displayed in Internet Explorer, is shown in Figure C-3.