import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.io.*; import java.sql.*; /* PhoneBook.java: Example of a middle-tier Java application - a servlet accessing a back-end database. Copyright (c) 1999 Nathan Meyers $Id: PhoneBook.java,v 1.6 1999/11/10 03:44:25 nathanm Exp $ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public class PhoneBook extends HttpServlet { Connection connection = null; public void init(ServletConfig config) throws ServletException { // Servlet initialization super.init(config); try { // Load the MySQL JDBC driver Class.forName("org.gjt.mm.mysql.Driver"); } catch (ClassNotFoundException e) { throw new ServletException(e.toString()); } } private void doOutput1(PrintWriter writer) { writer.println( "\n" + "\n" + "Phone Book" + "\n" + "\n" + "
\n" + "

Telephone Book

\n" + "
" + "\n" + "\n" + " \n" + " " + "\n" + " \n" + " " + "\n" + " \n" + " " + "\n" + " \n" + " " + "\n" + " \n" + " " + "\n" + "
Last Name
First Name
Country Code
Area Code
Phone Number
" + "\n" + "\n" + "\n" + "

" ); } private void doOutput2(PrintWriter writer) { writer.println(""); } public void doGet(HttpServletRequest req, HttpServletResponse resp) { // Get action puts up the query form. resp.setContentType("text/html"); PrintWriter writer = null; try { writer = resp.getWriter(); } catch (IOException e) { return; } doOutput1(writer); doOutput2(writer); writer.close(); } public synchronized void doPost(HttpServletRequest req, HttpServletResponse resp) { // Post action puts up the query form and responds to the post resp.setContentType("text/html"); PrintWriter writer = null; try { writer = resp.getWriter(); } catch (IOException e) { return; } // Output the form doOutput1(writer); // Open or reopen the connection if needed try { // Open a connection to the server - no login or password. // The form of the URL (first parameter) is dictated by the // MySQL jdbc driver. Default MySQL TCP port is 3306 if (connection == null || connection.isClosed()) connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "", ""); } catch (SQLException e) { writer.println("Error: Cannot open database connection\n"); doOutput2(writer); writer.close(); return; } // Open input from the POST data ServletInputStream instream = null; Hashtable postData = null; try { // Build a hashtable of the posted data postData = HttpUtils.parsePostData( req.getContentLength(), req.getInputStream()); } catch (IOException e) { writer.println("Error: Cannot read post data\n"); } if (postData.containsKey("Add")) { // User requested to add a new entry... make sure // at least last name is non-empty if (((String[])postData.get("LastName"))[0].length() == 0) writer.println("Error: No last name specified for Add"); else try { // Construct and execute an SQL statement to insert Statement stmt = connection.createStatement(); stmt.executeUpdate( "INSERT INTO phonelist VALUES (" + "'" + ((String[])postData.get("LastName"))[0] + "','" + ((String[])postData.get("FirstName"))[0] + "','" + ((String[])postData.get("CountryCode"))[0] + "','" + ((String[])postData.get("AreaCode"))[0] + "','" + ((String[])postData.get("PhoneNum"))[0] + "');"); writer.println("New entry added for " + ((String[])postData.get("LastName"))[0]); } catch (SQLException e) { writer.println("Error: " + e.toString()); } catch (NullPointerException e) { // This will trigger if a form field is missing from // the post. writer.println("Error: " + e.toString()); } } else { // User requested a query... ResultSet results = null; try { // Construct an SQL query string. First figure out // the qualifiers based on form input StringBuffer queryQualifiers = new StringBuffer(); appendQueryQualifiers(queryQualifiers, "lastname", (postData.get("LastName"))); appendQueryQualifiers(queryQualifiers, "firstname", (postData.get("FirstName"))); appendQueryQualifiers(queryQualifiers, "countrycode", (postData.get("CountryCode"))); appendQueryQualifiers(queryQualifiers, "areacode", (postData.get("AreaCode"))); appendQueryQualifiers(queryQualifiers, "number", (postData.get("PhoneNum"))); Statement stmt = connection.createStatement(); results = stmt.executeQuery( "SELECT * FROM phonelist" + queryQualifiers + ";" ); if (results == null) writer.println("Null result from query"); else { // Print headers writer.println( "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + ""); while (results.next()) { writer.println( "" + " \n" + " \n" + " \n" + " \n" + " \n" + ""); } writer.println("
Last Name
First Name
Country Code
Area Code
Phone Number
" + results.getString(1) + "" + results.getString(2) + "" + results.getString(3) + "" + results.getString(4) + "" + results.getString(5) + "
"); } } catch (SQLException e) { writer.println("Error: " + e.toString()); } } doOutput2(writer); writer.close(); } // appendQueryQualifiers: A utility to assist in constructing // the query string private void appendQueryQualifiers(StringBuffer qualifiers, String dbfield, Object formdata) { if (formdata == null) return; String forminfo = ((String[])formdata)[0]; // Was anything specified for this form field? if (forminfo.length() > 0) { // Yes if (qualifiers.length() == 0) qualifiers.append(" WHERE"); else qualifiers.append(" AND"); qualifiers.append(" " + dbfield + " = \"" + forminfo + "\""); } } public String getServletInfo() { return "PhoneBook"; } }