What s Next


Connecting through JSP

This chapter wouldn't be complete without a simple example of connecting to a database using a JSP page. The code in Listing 11.4 is a JSP page to pull the same data as in Listing 11.1.

Listing 11.4: JSP database access.

start example
 <%@ page import='java.sql.*, javax.sql.*, javax.naming.*' %> <HTML> <HEAD> <TITLE>MySQL JSP Example</TITLE> </HEAD> <BODY> <%   Context ic = new InitialContext();   DataSource ds = (DataSource)   ic.lookup("java:comp/env/jdbc/mysql");   Connection conn = ds.getConnection();   try {     Statement stmt = conn.createStatement();     ResultSet rs = stmt.executeQuery("SELECT title,       price FROM product"); %> <UL> <%   while (myResultSet.next()) { %>   <LI> <%     myResult.getString("title") + " "       + myResultSet.getString("price));   } %>   </UL> </BODY> </HTML> <% } catch(SQLException e) {     out.println("SQLException caught: "      + e.getMessage());   } } finally {     conn.close();   } %> 
end example

As you can see, a JSP page with embedded Java can use the JNDI configuration information provided in the resin.conf file. Once the database information has been obtained, the database is queried and the results are output to the browser, just as in the servlet code.




Mastering Resin
Mastering Resin
ISBN: 0471431036
EAN: 2147483647
Year: 2002
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net