slu

Søren's Blog

Random Ramblings

Previous Entry Share Next Entry
HSQLDB Part 3 - Java Server Pages
computer
slu
Now in the previous installment of my notes regarding HSQLDB, I presented a very simple console program. It would connect to the database and lists the contents of the Bookmarks-table to the console.

Below is a webified version of the program. It's implemented as a single JSP file, TestDemobase.jsp. Store it in your webapps directory ($CATALINA_HOME/webapps/app/).

Note: this is absolutely not the way to do it. The code below is ugly and difficult to maintain. It is meant as a very simple example of connecting to a database from JSP.

<%@ page language="java" 
           import="java.sql.Connection,
                   java.sql.DriverManager,
                   java.sql.ResultSet,
                   java.sql.Statement" %>

<%!
  String title = "Database Test";
  String database = ""; 
  String sql = "SELECT title, url FROM Bookmarks ORDER BY title";
  Connection connection = null;
  Statement statement = null;
  ResultSet resultSet = null;
%>

<%
  try {
    database = application.getRealPath("/database/demobase");
  
    Class.forName("org.hsqldb.jdbcDriver");
    connection = DriverManager.getConnection("jdbc:hsqldb:file:" +
                                             database, "sa", "");
  
    statement = connection.createStatement();
    resultSet = statement.executeQuery(sql);
  }
  catch (Exception e) {
    out.print("Unable do make connection database<br>");
    out.print(e);
  }
%>

<html>
  <head>
    <title><%=title%></title>
  </head>

  <body>

  <h1><%=title%></h1>

  <h2>Bookmarks</h2>

  <ul>

    <% while (resultSet.next()) { %>
      <li><a href="<%=resultSet.getObject("url")%>"><%=
          resultSet.getObject("title")%></a></li>
    <% } %>
  </ul>

  </body> 
</html>

<%
  resultSet.close();
  statement.close();
  connection.close();
%>

  • 1

NEVER Connect to a Database from a JSP

(Anonymous)
It's a really dumb thing to do. It's much better to use JSP's as *views* within a MVC approach. If you do things this way (e.g. "One on One J2EE Design & Development" by Rod Johnson) there is never ANY GOOD REASON to connect to the database from a JSP.

Re: NEVER Connect to a Database from a JSP

(Anonymous)
"Note: this is absolutely not the way to do it. The code below is ugly and difficult to maintain. It is meant as a very simple example of connecting to a database from JSP."

Re: NEVER Connect to a Database from a JSP

(Anonymous)
Get real man. This is a great example of MVC1. Sometimes it's the best. And the guy qualified it at the top of his page.

I really appreciate simple examples when it comes to learning a technology; it isolates what we're trying to learn here.

Thanks to the author for this work.

This was very helpful to me trying to connect to the database back-end of my subsonic media server. Cheers!

  • 1
?

Log in

No account? Create an account