Source of SurveyServlet.java


  1: // Fig. 26.21: SurveyServlet.java
  2: // A Web-based survey that uses JDBC from a servlet.
  3: package com.deitel.jhtp6.servlets;
  4: 
  5: import java.io.PrintWriter;
  6: import java.io.IOException;
  7: import java.sql.Connection;
  8: import java.sql.DriverManager;
  9: import java.sql.Statement;
 10: import java.sql.ResultSet;
 11: import java.sql.SQLException;
 12: import javax.servlet.ServletConfig;
 13: import javax.servlet.ServletException;
 14: import javax.servlet.UnavailableException;
 15: import javax.servlet.http.HttpServlet;
 16: import javax.servlet.http.HttpServletRequest;
 17: import javax.servlet.http.HttpServletResponse;
 18: 
 19: public class SurveyServlet extends HttpServlet 
 20: {
 21:    private Connection connection;
 22:    private Statement statement;
 23: 
 24:    // set up database connection and create SQL statement
 25:    public void init( ServletConfig config ) throws ServletException
 26:    {
 27:       // attempt database connection and create Statement
 28:       try 
 29:       {
 30:          Class.forName( config.getInitParameter( "databaseDriver" ) );
 31:          connection = DriverManager.getConnection( 
 32:             config.getInitParameter( "databaseName" ),
 33:             config.getInitParameter( "username" ),
 34:             config.getInitParameter( "password" ) );
 35: 
 36:          // create Statement to query database
 37:          statement = connection.createStatement();
 38:       } // end try
 39:       // for any exception throw an UnavailableException to 
 40:       // indicate that the servlet is not currently available
 41:       catch ( Exception exception ) 
 42:       {
 43:          exception.printStackTrace();
 44:          throw new UnavailableException( exception.getMessage() );
 45:       } // end catch
 46:    }  // end method init 
 47: 
 48:    // process survey response
 49:    protected void doPost( HttpServletRequest request,
 50:       HttpServletResponse response )
 51:          throws ServletException, IOException
 52:    {
 53:       // set up response to client
 54:       response.setContentType( "text/html" ); 
 55:       PrintWriter out = response.getWriter();
 56: 
 57:       // start XHTML document
 58:       out.println( "<?xml version = \"1.0\"?>" );
 59: 
 60:       out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC", 
 61:          " \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
 62:          " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
 63: 
 64:       out.println( 
 65:          "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
 66: 
 67:       // head section of document
 68:       out.println( "<head>" );  
 69:       
 70:       // read current survey response
 71:       int value = 
 72:          Integer.parseInt( request.getParameter( "animal" ) );
 73:       String sql;
 74: 
 75:       // attempt to process a vote and display current results
 76:       try 
 77:       {
 78:          // update total for current survey response
 79:          sql = "UPDATE surveyresults SET votes = votes + 1 " +
 80:                "WHERE id = " + value;
 81:          statement.executeUpdate( sql );
 82: 
 83:          // get total of all survey responses
 84:          sql = "SELECT sum( votes ) FROM surveyresults";
 85:          ResultSet totalRS = statement.executeQuery( sql );
 86:          totalRS.next(); // position to first record
 87:          int total = totalRS.getInt( 1 );
 88: 
 89:          // get results
 90:          sql = "SELECT surveyoption, votes, id FROM surveyresults " + 
 91:             "ORDER BY id";
 92:          ResultSet resultsRS = statement.executeQuery( sql );
 93:          out.println( "<title>Thank you!</title>" );
 94:          out.println( "</head>" );  
 95:          
 96:          out.println( "<body>" );  
 97:          out.println( "<p>Thank you for participating." );
 98:          out.println( "<br />Results:</p><pre>" );
 99:          
100:          // process results
101:          int votes;
102:          
103:          while ( resultsRS.next() ) 
104:          {
105:             out.print( resultsRS.getString( 1 ) );
106:             out.print( ": " );
107:             votes = resultsRS.getInt( 2 );
108:             out.printf( "%.2f", ( double ) votes / total * 100 );
109:             out.print( "%  responses: " );
110:             out.println( votes );
111:          } // end while
112: 
113:          resultsRS.close();
114:          
115:          out.print( "Total responses: " );
116:          out.print( total );
117:          
118:          // end XHTML document
119:          out.println( "</pre></body></html>" );         
120:          out.close();
121:       } // end try
122:       // if database exception occurs, return error page
123:       catch ( SQLException sqlException ) 
124:       {
125:          sqlException.printStackTrace();
126:          out.println( "<title>Error</title>" );
127:          out.println( "</head>" );  
128:          out.println( "<body><p>Database error occurred. " );
129:          out.println( "Try again later.</p></body></html>" );
130:          out.close();
131:       } // end catch
132:    } // end method doPost
133: 
134:    // close SQL statements and database when servlet terminates
135:    public void destroy()
136:    {
137:       // attempt to close statements and database connection
138:       try 
139:       {
140:          statement.close();
141:          connection.close();
142:       } // end try
143:       // handle database exceptions by returning error to client
144:       catch( SQLException sqlException ) 
145:       {
146:          sqlException.printStackTrace();
147:       } // end catch
148:    } // end method destroy
149: } // end class SurveyServlet
150: 
151: /**************************************************************************
152:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
153:  * Pearson Education, Inc. All Rights Reserved.                           *
154:  *                                                                        *
155:  * DISCLAIMER: The authors and publisher of this book have used their     *
156:  * best efforts in preparing the book. These efforts include the          *
157:  * development, research, and testing of the theories and programs        *
158:  * to determine their effectiveness. The authors and publisher make       *
159:  * no warranty of any kind, expressed or implied, with regard to these    *
160:  * programs or to the documentation contained in these books. The authors *
161:  * and publisher shall not be liable in any event for incidental or       *
162:  * consequential damages in connection with, or arising out of, the       *
163:  * furnishing, performance, or use of these programs.                     *
164:  *************************************************************************/