/** ----------------------------------------------------------------- * Copyright 1922 Sun Microcomputers, Inc., * and Mark Andrews. All rights reserved. * ----------------------------------------------------------------- * * FormDisplayServlet servlet * * This servlet reads items which the user has entered * in the Guestbook, and responds appropriately -- with * either a thank-you page or an "error-and-please-try-again" * message. Then it adds the user's input to a database. * * This servlet shows how to incorporate a guestbook page * or a registration page into a Web site. */ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.text.*; /** ----------------------------------------------------------------- * The FormDisplayServlet() class. * *@ param req Instance of class HttpServletRequest. *@ param res Instance of class HttpServletResponse. *@ exception IOException When inputting form data or writing * the form data back to the browser. */ ////////////////////////////////////////////////////////////// // // This method displays the form and gets user input. // public class FormDisplayServlet extends HttpServlet { int connections; // Variable to track number of visitors.. public final String BASENAME = "samples"; public final int NR_OF_PARAMS = 17; // Doesn't include check boxes. public final int MAX_CLASS_SIZE = 200; String userName; // String resources public final String s1 = "Guestbook Response Page"; public final String s2 = "Thanks for Signing Our Guestbook!"; public final String s3 = "Thank you for signing our guestbook! If you have requested" + "
"; public final String s4 = "information about setting up an e-commerce site," + "
"; public final String s5 = "we'll be getting back to you right away!" + "
"; public final String s6 = "Error: Registration file not found in your webserver doc root!
"; public final String s7 = "Please copy guestbook.txt to your servlets directory!
"; public final String s8 = "It looks like some information is missing from your guestbook form."; public final String s9 = "Please go back and fill in the following items so we can continue:"; public final String s10 = "Thank you for signing our guestbook! Everything you have" + "
"; public final String s11 = "shared with us will be kept strictly confidential." + "
"; /** ----------------------------------------------------------------- *@ The init() method. *@ *@ Initializes the servlet when the servlet is first loaded. */ ////////////////////////////////////////////////////////////// // // Here's the init() method. // public void init(ServletConfig config) throws ServletException { super.init(config); connections = 0; } //Process the HTTP Post request boolean error; String want_offers = "YES"; String want_info = "YES"; Enumeration params; String[] entries = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""}; // This servlet keeps track of a lot of strings. // These are the names of variables. public final String[] parms = {"firstname", // 0 "lastname", // 1 "age", // 2 "profession", // 3 "email", // 4 "homepage", // 5 "address1", // 6 "address2", // 7 "city", // 8 "state", // 9 "zipcode", //10 "country", //11 "areacode", //12 "phone", //13 "faxareacode",//14 "faxnumber", //15 "comments", //16 "want_offers",//17 "want_info" //18 }; // These are the same variables, expressed as // labels that are written in English and look nicer // on the page. public final String[] labels = {"First Name", // 0 "Last Name", // 1 "Age", // 2 "Profession", // 3 "Email", // 4 "Home Page", // 5 "Address 1", // 6 "Address 2", // 7 "City", // 8 "State/Province", // 9 "Zip/Postal Code", //10 "Country", //11 "Area/Country Code", //12 "Phone", //13 "Fax Area Code",//14 "Fax Number", //15 "Comments", //16 "Send Offers",//17 "Send Info" //18 }; ////////////////////////////////////////////////////////////// // // This is the all-important doPost() method. // public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // This line tells the servlet where the database is. String guestbook = request.getRealPath("guestbook.txt"); //First name String firstname = ""; try { firstname = request.getParameter("firstname"); } catch (Exception e) { e.printStackTrace(); } userName = firstname; //Last name String lastname = ""; try { lastname = request.getParameter("lastname"); } catch (Exception e) { e.printStackTrace(); } //Age String age = "Select One"; try { age = request.getParameter("age"); } catch (Exception e) { e.printStackTrace(); } //Profession String profession = ""; try { profession = request.getParameter("profession"); } catch (Exception e) { e.printStackTrace(); } //Email Address String email = ""; try { email = request.getParameter("email"); } catch (Exception e) { e.printStackTrace(); } //Home Page String homepage = "http://"; try { homepage = request.getParameter("homepage"); } catch (Exception e) { e.printStackTrace(); } //Street Address String address1 = ""; try { address1 = request.getParameter("address1"); } catch (Exception e) { e.printStackTrace(); } //Apt. No., etc. String address2 = ""; try { address2 = request.getParameter("address2"); } catch (Exception e) { e.printStackTrace(); } //City String city = ""; try { city = request.getParameter("city"); } catch (Exception e) { e.printStackTrace(); } //State/Province String state = ""; try { state = request.getParameter("state"); } catch (Exception e) { e.printStackTrace(); } //Zip/Postal Code String zipcode = ""; try { zipcode = request.getParameter("zipcode"); } catch (Exception e) { e.printStackTrace(); } //Country String country = "Select One"; try { country = request.getParameter("country"); } catch (Exception e) { e.printStackTrace(); } //Area/Country Code String areacode = ""; try { areacode = request.getParameter("areacode"); } catch (Exception e) { e.printStackTrace(); } //Phone Number String phone = ""; try { phone = request.getParameter("phone"); } catch (Exception e) { e.printStackTrace(); } //Fax Area Code String faxareacode = ""; try { faxareacode = request.getParameter("faxareacode"); } catch (Exception e) { e.printStackTrace(); } //Fax Number String faxnumber = ""; try { faxnumber = request.getParameter("faxnumber"); } catch (Exception e) { e.printStackTrace(); } //Comments String comments = ""; try { comments = request.getParameter("comments"); } catch (Exception e) { e.printStackTrace(); } response.setContentType("text/html"); PrintWriter pw = new PrintWriter (response.getOutputStream()); pw.println(""); pw.println("GuestBookServlet"); pw.println(""); /* // These operations were in a JBuilder tutorial. // They worked well, and I might put them to // some use someday. // // pw.print("

You are visitor number "); // connections++; // pw.println(Integer.toString(connections)); // pw.print(".

"); // End tutorial print operations. */ // Find out if the user left any items blank. params = request.getParameterNames(); String s; String b = "BLANK"; String dbString = ""; error = false; // Check carefully to see if any items are blank. for (int n = 0; n < NR_OF_PARAMS; n++) { s = request.getParameter(parms[n]); if (s.length() == 0) { // Some fields aren't required, thus // can be left blank without generating errors. switch (n) { // These are the important ones. case 0: // firstname case 1: // lastname case 4: // email case 8: // city case 9: // state case 10: // zipcode case 11: // country entries[n] = "ERROR"; error = true; break; // These are optional. case 2: // age case 3: // profession case 5: // homepage case 6: // address1 case 7: // address2 case 12: // areacode case 13: // phone case 14: // faxareacode case 15: // faxnumber case 16: // comments case 17: // want_offers case 18: // want_info entries[n] = "BLANK"; } } // This is the string that gets printed to the // database. Items are separated by the "|" character. dbString = dbString + s + "|"; } // Get the check-box parameters at the bottom of // the form. if (request.getParameter("want_offers") == null) want_offers = "NO"; if (request.getParameter("want_info") == null) want_info = "NO"; // This *ends* the string that gets printed to the // text file. It adds the checkbox responses // to the end of the input data. dbString = dbString + want_offers + "|"; dbString = dbString + want_info; // If any required field has been left blank, // we display an error page. if (error == true) { params = request.getParameterNames(); printErrorPage(pw, params, true); } // If no important items have been left blank, // we display the Thank You HTML page and update the // database with the user's input. else { // This is the method that prints the data to the database // and displays the Thank You HTML page. printData(null, null, dbString, guestbook, pw); } pw.println(""); pw.close(); } /** ------------------------------------------------------------- * The printErrorPage() method. * * Opens registration location file and writes * registration data to file * * @param pw PrintWriter. * @param Vector arg parameter Vector. * @boolean errorStatus. * @return Boolean indicating whether database entry was * successful. * @exception IOException When opening, reading from, or * writing the output stream to the registration file. */ ////////////////////////////////////////////////////////// // // This method outputs error messages to the browser page. // public void printErrorPage(PrintWriter pw, Enumeration e, boolean errorStatus) throws IOException { // This loop prints the error message. pw.print("

Oops!

"); pw.print("
"); pw.print(s8 + "
"); pw.println(s9 + "

"); for (int n = 0; n < NR_OF_PARAMS; n++) { if (entries[n] == "ERROR") { pw.println(labels[n]); pw.print("
"); entries[n] = ""; } } pw.println(""); pw.flush(); pw.close(); return; } // end of printErrorPage() /** ----------------------------------------------------------------- * @ printData() method. * * @ Displays a Thank You page and writes * data to the database. * * @param dt date -- not used in this implemementation. * @param loc -- not used in this implemementation. * @param rData Data string. * @param aFile Data file name. * @return Boolean indicating whether data was * successfully written. * * @exception IOException When opening, reading from, or * writing the output stream to the database. */ ////////////////////////////////////////////////////////// // // Display a Thank You page and add // the user's input to the database. // public synchronized boolean printData(String dt, String loc, String rData, String aFile, PrintWriter pw) throws IOException { boolean done = false; int numLns = 0; String line = null, regLine = null; String fileLine = null; String regFile = aFile; String regData = rData; BufferedReader readFile = null; Vector lines = new Vector(); // Set up a buffer to read out items that are // already in the database. try { // Heading for the Thank You page. pw.print("

Thanks for your feedback, " + userName + "!

"); pw.println(s10); pw.println(s11); // This is a test. // pw.println("RegData: " + regData + "
"); readFile = new BufferedReader(new FileReader(regFile)); } catch(Exception e) { pw.println(s6); pw.println(s7); pw.println(e.toString()); pw.flush(); return done; } ////////////////////////////////////////////////// // // Copy all current lines in the database // into a Vector. How inefficient! We need // an RDBMS. // while((regLine = readFile.readLine()) != null) { lines.addElement((Object)regLine); } pw.flush(); readFile.close(); // Check to see if we can write to the database. try { pw = new PrintWriter(new FileWriter(regFile)); } catch(Exception e) { pw.println("Error: Could not write to file " + regFile); pw.println(e.toString()); pw.flush(); return done; } //This loop adds the user's input to the database; if((numLns = lines.size()) > 0) { for(int i = 0;i < numLns;i++) { line = (String)lines.elementAt(i); pw.println(line); } // This is the line that does the writing // to the database file. pw.println(regData); done = true; } pw.flush(); pw.close(); return done; } // end of printData() } // end of class FormDisplayServlet