Accessing Databases in JSP


Creating HTML Tables from  ResultSet Objects

Click here to download the demo project

  public void displayResultSetHtml(ResultSet rs,javax.servlet.jsp.JspWriter out)
  
  {
     try{
       ResultSetMetaData rsmd = rs.getMetaData(); // get result set meta data
      
out.println("<table cellspacing = 10>");
         //
         // add column headers to the table
         //
         out.println("<tr>");
         for(int i = 1; i <= rsmd.getColumnCount(); i++)
         {
          out.println("<th>"+rsmd.getColumnLabel(i)+"</th>");  
         }
         out.println("</tr>");
        
         //
         // add row data to the table one row at a time
         //
         while(rs.next()) {
          out.println("<tr>");
          for(int i = 1; i <= rsmd.getColumnCount(); i++)
          {
            out.println("<td>"+rs.getString(i)+"</td>");
          }
          out.println("</tr>");
         } 
         out.println("</table>");
       }
       catch(Exception e)
        {
        System.out.println("Error processing result set : "+e.getMessage());        
       }
    }

 

Creating shopping lists

<a href = 'orderItem.jsp?action=Add&upc=2202&name=bolts&quantity=1&price=1.23'> add to cart </a>
    out.println("<td><a href = 'orderItem.jsp?action=Add&upc="+upc+"&name="+name+"&price="+price+"&quantity=1' target='shoppingcart'> add to cart </a></td>");   


OrderProducts.html

<html>
    <head>
        <title>Order Products</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <h2>Search for products</h2>
        <form name="orderproducts" method="get" action="orderProducts.jsp" target="searchresults">
            <table>
                <tr><td>Enter all or part of a name :</td><td><input type="text" name="productname" size="25"></td></tr>   
                <tr><td>Enter maximum price :</td><td><input type="text" name="maxprice" size="10" value="1000"></td></tr> 
                <tr><td colspan ="2"><br><input type ="submit" value="Search" name="action"><input type="reset" value="Clear"></td></tr>
            </table>
           
        </form>
        <p></p>
        <iframe width="600" height="300" name="searchresults"></iframe>
        <iframe width="600" height="200" name="shoppingcart"></iframe>
    </body>
</html>


 orderProducts.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="onlinecompany.*" %>
<%@page import="java.sql.*" %>      
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Search Results</title>
    </head>
    <body>
        <%!
       
          java.text.DecimalFormat currency = new java.text.DecimalFormat("$#,##0.00");
        %>
<%
    session.setMaxInactiveInterval(1800);  // 30 minutes
    try{
        String namefield = request.getParameter("productname");
        double maxprice = Double.parseDouble(request.getParameter("maxprice"));
       
        Database db = null;
        synchronized(session)
        {
          db = (Database)session.getAttribute("db");
          if(db == null)
          {
            db = new Database();
            session.setAttribute("db", db);            
          }
        }
      
        if(db == null || !db.connect())
        {
         out.println("Unable to connect to database");   
        }
        else // database ready to go
        {
          PreparedStatement prep = db.getConnection().prepareStatement("Select UPC,ProductName, Price from Products where ProductName like ? and Price <= ?");
          prep.setString(1,"%"+namefield+"%");
          prep.setDouble(2,maxprice);
          ResultSet rs = prep.executeQuery();
          out.println("<table cellspacing=5>");
          while(rs.next())
          {
           String upc = rs.getString(1);
           String name = rs.getString(2);
           double price = rs.getDouble(3);
          
           out.println("<tr>");
           out.println("<td>"+upc+"</td>");
           out.println("<td>"+name+"</td>");
           out.println("<td>"+currency.format(price)+"</td>");
          
           out.println("<td><a href = 'orderItem.jsp?action=Add&upc="+upc+"&name="+name+"&price="+price+"&quantity=1' target='shoppingcart'> add to cart </a></td>");   
           out.println("</tr>");
          }
          out.println("</table>");
         
          prep.close();
        }
        db.closeConnection();
       
    }
    catch(Exception ex)
    {
      System.err.println(ex.toString());            
    }

%>                              
    </body>
</html>