Søren Lund (slu) wrote,
Søren Lund

  • Mood:

HSQLDB Part 5 - Using a Bean

I my previous entry I created a JSP Document, which is the way I prefer to write JSP's. However there were still a little too much coding going on in the JSP, so I've take the main part of the code and put it in a class. The class is then used from the JSP Document with a jsp:useBean-tag. I'm still using the core tags of JSTL to render the page, but have moved all database-related code to the Bean.

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"

  <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">
      <title><c:out value="${title}" /></title>


      <h1><c:out value="${title}" /></h1>
        <c:forEach var="row" items="${bookmarks.links}">
            <c:out value="&lt;a href='${row.value}'&gt;${row.key}&lt;/a&gt;" 
               escapeXml="false" />



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 {
	    connection = DriverManager.getConnection("jdbc:hsqldb:" + 
						     database, "sa", "");
	    statement = connection.createStatement();
	    resultSet = statement.executeQuery(sql);
	    while (resultSet.next()) {
	catch (Exception e) {
	finally {
	    try {
	    catch (Exception e) {
	return links;

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded 

  • 1 comment