|
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.
<%@ 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(); } %>
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.
|