?
Solved

JAva-based Survey Servlet help comes with my code

Posted on 2004-11-17
3
Medium Priority
?
275 Views
Last Modified: 2013-11-24
I have written a short code about a simple survey servlet that submits results.  My question or favor is, can someone help me develop some code on how I can allow a user to view the results of the survey without responding to the survey?

Here is my code:

// A Web-based survey that uses JDBC from a servlet.

import java.io.PrintWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SurveyServlet extends HttpServlet
{
   private Connection connection;
   private Statement statement;

   // set up database connection and create SQL statement
   public void init( ServletConfig config ) throws ServletException
   {
      // attempt database connection and create Statement
      try
      {
         Class.forName( config.getInitParameter( "databaseDriver" ) );
         connection = DriverManager.getConnection(
            config.getInitParameter( "databaseName" ),
            config.getInitParameter( "username" ),
            config.getInitParameter( "password" ) );

         // create Statement to query database
         statement = connection.createStatement();
      } // end try
      // for any exception throw an UnavailableException to
      // indicate that the servlet is not currently available
      catch ( Exception exception )
      {
         exception.printStackTrace();
         throw new UnavailableException( exception.getMessage() );
      } // end catch
   }  // end method init

   // process survey response
   protected void doPost( HttpServletRequest request,
      HttpServletResponse response )
         throws ServletException, IOException
   {
      // set up response to client
      response.setContentType( "text/html" );
      PrintWriter out = response.getWriter();

      // start XHTML document
      out.println( "<?xml version = \"1.0\"?>" );

      out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
         " \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
         " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );

      out.println(
         "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

      // head section of document
      out.println( "<head>" );  
     
      // read current survey response
      int value =
         Integer.parseInt( request.getParameter( "animal" ) );
      String sql;

      // attempt to process a vote and display current results
      try
      {
         // update total for current survey response
         sql = "UPDATE surveyresults SET votes = votes + 1 " +
               "WHERE id = " + value;
         statement.executeUpdate( sql );

         // get total of all survey responses
         sql = "SELECT sum( votes ) FROM surveyresults";
         ResultSet totalRS = statement.executeQuery( sql );
         totalRS.next(); // position to first record
         int total = totalRS.getInt( 1 );

         // get results
         sql = "SELECT surveyoption, votes, id FROM surveyresults " +
            "ORDER BY id";
         ResultSet resultsRS = statement.executeQuery( sql );
         out.println( "<title>Thank you!</title>" );
         out.println( "</head>" );  
         
         out.println( "<body>" );  
         out.println( "<p>Thank you for participating." );
         out.println( "<br />Results:</p><pre>" );
         
         // process results
         int votes;
         
         while ( resultsRS.next() )
         {
            out.print( resultsRS.getString( 1 ) );
            out.print( ": " );
            votes = resultsRS.getInt( 2 );
            out.printf( "%.2f", ( double ) votes / total * 100 );
            out.print( "%  responses: " );
            out.println( votes );
         } // end while

         resultsRS.close();
         
         out.print( "Total responses: " );
         out.print( total );
         
         // end XHTML document
         out.println( "</pre></body></html>" );        
         out.close();
      } // end try
      // if database exception occurs, return error page
      catch ( SQLException sqlException )
      {
         sqlException.printStackTrace();
         out.println( "<title>Error</title>" );
         out.println( "</head>" );  
         out.println( "<body><p>Database error occurred. " );
         out.println( "Try again later.</p></body></html>" );
         out.close();
      } // end catch
   } // end method doPost

   // close SQL statements and database when servlet terminates
   public void destroy()
   {
      // attempt to close statements and database connection
      try
      {
         statement.close();
         connection.close();
      } // end try
      // handle database exceptions by returning error to client
      catch( SQLException sqlException )
      {
         sqlException.printStackTrace();
      } // end catch
   } // end method destroy
} // end class SurveyServlet
0
Comment
Question by:djchiena
1 Comment
 
LVL 1

Accepted Solution

by:
Lucky48390 earned 1000 total points
ID: 12610589
I would keep the portion that displays results separate from your servlet. You need a SurveyResults class so that you can display results weather a survey is submitted or not.

Also, please read the section "How a servlet is destroyed" in this document: http://java.sun.com/products/servlet/2.1/html/introduction.fm.html

Your statement and connection objects should not be closed in your destroy method. You should put them in a finally block at the bottom of your doPost(). Hope that helps a little
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month14 days, 12 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question