Java tutorial
/** * Copyright (c) 2002 by Phil Hanna * All rights reserved. * * You may study, use, modify, and distribute this * software for any purpose provided that this * copyright notice appears in all copies. * * This software is provided without warranty * either expressed or implied. */ import java.io.*; import java.net.*; import java.sql.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /** * Returns the list of the most popular flavors */ public class FlavorListServlet extends HttpServlet { public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; public static final String URL = "jdbc:mysql://localhost/IceCream"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); // Get the bounds of the ranks to be listed // or use defaults int lowLimit = getLimit(request.getParameter("lowLimit"), 0); int highLimit = getLimit(request.getParameter("highLimit"), 100); Connection con = null; try { // Connect to the ice cream database Class.forName(JDBC_DRIVER); con = DriverManager.getConnection(URL); // Run a query to get the top flavors String sql = "SELECT RANK, NAME" + " FROM flavors" + " WHERE RANK BETWEEN ? AND ?" + " ORDER BY RANK"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, lowLimit); pstmt.setInt(2, highLimit); ResultSet rs = pstmt.executeQuery(); // Print as an ordered list out.println("<ol>"); while (rs.next()) { int rank = rs.getInt(1); String name = rs.getString(2); out.println(" <li>" + name + "</li>"); } out.println("</ol>"); } catch (SQLException e) { throw new ServletException(e.getMessage()); } catch (ClassNotFoundException e) { throw new ServletException(e.getMessage()); } // Close the database finally { if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } } /** * Subroutine to get the integer value of one of * the limit parameters. * @param parm the parameter value, which may be null * @param defaultValue the default value */ private static int getLimit(String parm, int defaultValue) { int limit = defaultValue; if (parm != null) { try { limit = Integer.parseInt(parm); } catch (NumberFormatException ignore) { } } return limit; } }