Here's first the new and improved JSP Document:
<?xml version="1.0" encoding="iso-8859-1"?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2" xmlns:c="http://java.sun.com/jstl/core"> <jsp:directive.page contentType="text/html; charset=iso-8859-1" /> <c:set var="title" value="Database Test" /> <jsp:useBean id="bookmarks" scope="session" class="soren.Bookmarks" /> <c:set target="${bookmarks}" property="database"> <jsp:scriptlet> out.print(application.getRealPath("/database/demobase")); </jsp:scriptlet> </c:set> <html> <head> <title><c:out value="${title}" /></title> </head> <body> <h1><c:out value="${title}" /></h1> <h2>Bookmarks</h2> <ul> <c:forEach var="row" items="${bookmarks.links}"> <li> <c:out value="<a href='${row.value}'>${row.key}</a>" escapeXml="false" /> </li> </c:forEach> </ul> </body> </html> </jsp:root>
This is actually what I would consider production quality code, except for the scriptlet code that sets the database property in the bookmarks Bean. This should be placed in a properties file or defined with JNDI in the servlet container.
Next create the Bookmarks.java file and compile it. Place the resulting Bookmarks.class file in a directory called soren in your WEB-INF/classes directory. This is still not production quality code, but it's getting closer.
package soren; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; import java.util.Map; public class Bookmarks { String sql = "SELECT title, url FROM Bookmarks ORDER BY title"; String database = ""; HashMap links = null; public Bookmarks() { links = new HashMap(); } public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } public synchronized Map getLinks() { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("org.hsqldb.jdbcDriver"); connection = DriverManager.getConnection("jdbc:hsqldb:" + database, "sa", ""); statement = connection.createStatement(); resultSet = statement.executeQuery(sql); while (resultSet.next()) { links.put(resultSet.getString("title"), resultSet.getString("url")); } } catch (Exception e) { e.printStackTrace(); } finally { try { resultSet.close(); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return links; } }