/Users/lyon/j4p/src/net/server/servlets/PhoneBook.java

1    package net.server.servlets; 
2     
3    import javax.servlet.ServletConfig; 
4    import javax.servlet.ServletException; 
5    import javax.servlet.http.HttpServlet; 
6    import javax.servlet.http.HttpServletRequest; 
7    import javax.servlet.http.HttpServletResponse; 
8    import javax.servlet.http.HttpUtils; 
9    import java.io.IOException; 
10   import java.io.PrintWriter; 
11   import java.sql.*; 
12   import java.util.Hashtable; 
13    
14   /* 
15        PhoneBook.java: 
16       Example of a middle-tier Java application - a servlet 
17       accessing a back-end database. 
18    
19        Copyright (c) 1999 Nathan Meyers 
20        $Id: PhoneBook.java,v 1.6 1999/11/10 03:44:25 nathanm Exp $ 
21    
22        Permission is hereby granted, free of charge, to any person obtaining 
23        a copy of this software and associated documentation files (the 
24        "Software"), to deal in the Software without restriction, including 
25        without limitation the rights to use, copy, modify, merge, publish, 
26        distribute, sublicense, and/or sell copies of the Software, and to 
27        permit persons to whom the Software is furnished to do so, subject 
28        to the following conditions: 
29    
30        The above copyright notice and this permission notice shall be 
31        included in all copies or substantial portions of the Software. 
32    
33        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 
34        KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
35        WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
36        NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 
37        BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN 
38        AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
39        IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
40        THE SOFTWARE. 
41   */ 
42    
43   public class PhoneBook extends HttpServlet { 
44       Connection connection = null; 
45    
46       public void init(ServletConfig config) throws ServletException { 
47           // Servlet initialization 
48           super.init(config); 
49           try { 
50               // Load the MySQL JDBC driver 
51               Class.forName("org.gjt.mm.mysql.Driver"); 
52           } catch (ClassNotFoundException e) { 
53               throw new ServletException(e.toString()); 
54           } 
55       } 
56    
57       private void doOutput1(PrintWriter writer) { 
58           writer.println( 
59                   "<HTML>\n" + 
60                   "<HEAD>\n" + 
61                   "<TITLE>Phone Book</TITLE>" + 
62                   "</HEAD>\n" + 
63                   "<BODY>\n" + 
64                   "<CENTER>\n" + 
65                   "<H1>Telephone Book</H1>\n" + 
66                   "<FORM ACTION=\"PhoneBook\" METHOD=\"POST\">" + 
67                   "<TABLE>\n" + 
68                   "<TR>\n" + 
69                   "  <TD>Last Name</TD>\n" + 
70                   "  <TD><INPUT TYPE=\"TEXT\" SIZE=20 NAME=\"LastName\"></TD>" + 
71                   "</TR><TR>\n" + 
72                   "  <TD>First Name</TD>\n" + 
73                   "  <TD><INPUT TYPE=\"TEXT\" SIZE=20 NAME=\"FirstName\"></TD>" + 
74                   "</TR><TR>\n" + 
75                   "  <TD>Country Code</TD>\n" + 
76                   "  <TD><INPUT TYPE=\"TEXT\" SIZE=5 NAME=\"CountryCode\"></TD>" + 
77                   "</TR><TR>\n" + 
78                   "  <TD>Area Code</TD>\n" + 
79                   "  <TD><INPUT TYPE=\"TEXT\" SIZE=5 NAME=\"AreaCode\"></TD>" + 
80                   "</TR><TR>\n" + 
81                   "  <TD>Phone Number</TD>\n" + 
82                   "  <TD><INPUT TYPE=\"TEXT\" SIZE=15 NAME=\"PhoneNum\"></TD>" + 
83                   "</TR>\n" + 
84                   "</TABLE>" + 
85                   "<INPUT TYPE=\"Submit\" NAME=\"Query\" VALUE=\"Query\">\n" + 
86                   "<INPUT TYPE=\"Submit\" NAME=\"Add\" VALUE=\"Add New Entry\">\n" + 
87                   "<INPUT TYPE=\"Reset\" VALUE=\"Reset\">\n" + 
88                   "</FORM><BR>" 
89           ); 
90       } 
91    
92       private void doOutput2(PrintWriter writer) { 
93           writer.println("</BODY></HTML>"); 
94       } 
95    
96       public void doGet(HttpServletRequest req, HttpServletResponse resp) { 
97           // Get action puts up the query form. 
98           resp.setContentType("text/html"); 
99           PrintWriter writer = null; 
100          try { 
101              writer = resp.getWriter(); 
102          } catch (IOException e) { 
103              return; 
104          } 
105          doOutput1(writer); 
106          doOutput2(writer); 
107          writer.close(); 
108      } 
109   
110      public synchronized void doPost(HttpServletRequest req, 
111                                      HttpServletResponse resp) { 
112          // Post action puts up the query form and responds to the post 
113          resp.setContentType("text/html"); 
114          PrintWriter writer = null; 
115          try { 
116              writer = resp.getWriter(); 
117          } catch (IOException e) { 
118              return; 
119          } 
120   
121          // Output the form 
122          doOutput1(writer); 
123   
124          // Open or reopen the connection if needed 
125          try { 
126              // Open a connection to the server - no login or password. 
127              // The form of the URL (first parameter) is dictated by the 
128              // MySQL jdbc driver. Default MySQL TCP port is 3306 
129              if (connection == null || connection.isClosed()) 
130                  connection = DriverManager.getConnection( 
131                          "jdbc:mysql://localhost:3306/test", "lyon", null); 
132          } catch (SQLException e) { 
133              writer.println("Error: Cannot open database connection\n"); 
134              doOutput2(writer); 
135              writer.close(); 
136              return; 
137          } 
138   
139          // Open input from the POST data 
140          Hashtable postData = null; 
141          try { 
142              // Build a hashtable of the posted data 
143              postData = HttpUtils.parsePostData( 
144                      req.getContentLength(), req.getInputStream()); 
145          } catch (IOException e) { 
146              writer.println("Error: Cannot read post data\n"); 
147          } 
148          if (postData.containsKey("Add")) { 
149              // User requested to add a new entry... make sure 
150              // at least last name is non-empty 
151              if (((String[]) postData.get("LastName"))[0].length() == 0) 
152                  writer.println("Error: No last name specified for Add"); 
153              else 
154                  try { 
155                      // Construct and execute an SQL statement to insert 
156                      Statement stmt = connection.createStatement(); 
157                      stmt.executeUpdate( 
158                              "INSERT INTO phonelist VALUES (" + 
159                              "'" + 
160                              ((String[]) postData.get("LastName"))[0] + 
161                              "','" + 
162                              ((String[]) postData.get("FirstName"))[0] + 
163                              "','" + 
164                              ((String[]) postData.get("CountryCode"))[0] + 
165                              "','" + 
166                              ((String[]) postData.get("AreaCode"))[0] + 
167                              "','" + 
168                              ((String[]) postData.get("PhoneNum"))[0] + 
169                              "');"); 
170                      writer.println("New entry added for " + 
171                              ((String[]) postData.get("LastName"))[0]); 
172                  } catch (SQLException e) { 
173                      writer.println("Error: " + e.toString()); 
174                  } catch (NullPointerException e) { 
175                      // This will trigger if a form field is missing from 
176                      // the post. 
177                      writer.println("Error: " + e.toString()); 
178                  } 
179          } else { 
180              // User requested a query... 
181              ResultSet results = null; 
182              try { 
183                  // Construct an SQL query string. First figure out 
184                  // the qualifiers based on form input 
185                  StringBuffer queryQualifiers = new StringBuffer(); 
186                  appendQueryQualifiers(queryQualifiers, "lastname", 
187                          (postData.get("LastName"))); 
188                  appendQueryQualifiers(queryQualifiers, "firstname", 
189                          (postData.get("FirstName"))); 
190                  appendQueryQualifiers(queryQualifiers, "countrycode", 
191                          (postData.get("CountryCode"))); 
192                  appendQueryQualifiers(queryQualifiers, "areacode", 
193                          (postData.get("AreaCode"))); 
194                  appendQueryQualifiers(queryQualifiers, "number", 
195                          (postData.get("PhoneNum"))); 
196   
197                  Statement stmt = connection.createStatement(); 
198                  results = stmt.executeQuery( 
199                          "SELECT * FROM phonelist" + 
200                          queryQualifiers + 
201                          ";" 
202                  ); 
203   
204                  if (results == null) 
205                      writer.println("Null result from query"); 
206                  else { 
207                      // Print headers 
208                      writer.println( 
209                              "<TABLE BORDER=\"2\">\n" + 
210                              "<TR>\n" + 
211                              "  <TD><CENTER><B>Last Name</B></CENTER></TD>\n" + 
212                              "  <TD><CENTER><B>First Name</B></CENTER></TD>\n" + 
213                              "  <TD><CENTER><B>Country Code</B></CENTER></TD>\n" + 
214                              "  <TD><CENTER><B>Area Code</B></CENTER></TD>\n" + 
215                              "  <TD><CENTER><B>Phone Number</B></CENTER></TD>\n" + 
216                              "</TR>"); 
217   
218                      while (results.next()) { 
219                          writer.println( 
220                                  "<TR>" + 
221                                  "  <TD>" + results.getString(1) + "</TD>\n" + 
222                                  "  <TD>" + results.getString(2) + "</TD>\n" + 
223                                  "  <TD>" + results.getString(3) + "</TD>\n" + 
224                                  "  <TD>" + results.getString(4) + "</TD>\n" + 
225                                  "  <TD>" + results.getString(5) + "</TD>\n" + 
226                                  "</TR>"); 
227                      } 
228                      writer.println("</TABLE>"); 
229                  } 
230              } catch (SQLException e) { 
231                  writer.println("Error: " + e.toString()); 
232              } 
233          } 
234          doOutput2(writer); 
235          writer.close(); 
236      } 
237   
238      // appendQueryQualifiers: A utility to assist in constructing 
239      // the query string 
240      private void appendQueryQualifiers(StringBuffer qualifiers, 
241                                         String dbfield, 
242                                         Object formdata) { 
243          if (formdata == null) return; 
244          String forminfo = ((String[]) formdata)[0]; 
245          // Was anything specified for this form field? 
246          if (forminfo.length() > 0) { 
247              // Yes 
248              if (qualifiers.length() == 0) 
249                  qualifiers.append(" WHERE"); 
250              else 
251                  qualifiers.append(" AND"); 
252              qualifiers.append(" " + dbfield + " = \"" + 
253                      forminfo + "\""); 
254          } 
255      } 
256   
257      public String getServletInfo() { 
258          return "PhoneBook"; 
259      } 
260  } 
261