ServletExample.sqlj 2.41 KB
Newer Older
O'Reilly Media, Inc. committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
/*
   ServletExample.sqlj illustrates how to include
   SQLJ statements in a servlet.
*/

// import the servlet, io, and util classes
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

// import the SQLJ classes
import java.sql.*;
import oracle.sqlj.runtime.Oracle;
import sqlj.runtime.ref.DefaultContext;

public class ServletExample extends HttpServlet {

  // declare an iterator class
  #sql private static iterator CustIteratorClass(
    int           id,
    String        first_name,
    String        last_name,
    java.sql.Date dob,
    String        phone
  );

  // handle get request
  public void doGet(
    HttpServletRequest req,
    HttpServletResponse res
  ) throws ServletException, IOException {

    // output HTML
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<html><head><title>Customers</title></head>");
    out.println("<body>");

    // retrieve and display the customer details
    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
      };

      // write the customer details out to an HTML table
      out.println("<table width=100% border=1>");
      out.println("<tr>");
      out.println("<th>Id</th>");
      out.println("<th>First Name</th>");
      out.println("<th>Last Name</th>");
      out.println("<th>DOB</th>");
      out.println("<th>Phone</th>");
      out.println("</tr>");

      while (cust_iterator.next()) {

        out.println("<tr>");
        out.println("<td>" + cust_iterator.id() + "</td>");
        out.println("<td>" + cust_iterator.first_name() + "</td>");
        out.println("<td>" + cust_iterator.last_name() + "</td>");
        out.println("<td>" + cust_iterator.dob() + "</td>");
        out.println("<td>" + cust_iterator.phone() + "</td>");
        out.println("</tr>");

      } // end of while

      cust_iterator.close();
      conn_context.close();

      out.println("</table>");
      out.println("</body></html>");

    } catch ( SQLException e ) {

      out.println("SQLException " + e);

    }
  }
}