tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Martin Gainty" <mgai...@hotmail.com>
Subject Re: Need Help w. Database Servlet.
Date Sun, 28 Jan 2007 22:46:18 GMT
The init method is meant to init the servlet itself
Each statement executed causes a DB cursor to be created to execute the operation
e.g. ReadCursor for executeQuery
e.g. UpdateCursor for executeUpdate

public class SurveyServlet extends HttpServlet {
   private Connection connection;
   private String fu;
   private String bar;
   private PreparedStatement updateVotes, totalVotes, results; 

//if anything causing servletException inside this init methid would be thrown your servlet
will cause 503 or 500 or some exception which will throw
//ServletException
   public void init( ServletConfig config ) throws ServletException
  {
    fu="fu";
    bar="bar";
   }

//Once init'ed I would wait for DoPost or DoGet or service methods for the following sequence
   protected void doPost( HttpServletRequest request,HttpServletResponse response ) throws
ServletException, IOException
   {
      // set up response to client
      response.setContentType( "text/html" );
      PrintWriter out = response.getWriter();
      DecimalFormat twoDigits = new DecimalFormat( "0.00" );
 
      // start XHTML document
      out.println( "<?xml version = \"1.0\"?>" );
 
      out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
         "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
         "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
 
      out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
 
      // head section of document
      out.println( "<head>" );  

      try 
     { //load the Driver
         Class.forName( "COM.cloudscape.core.RmiJdbcDriver" );
        //acquire a Connection from the DriverManager
         connection = DriverManager.getConnection(
            "jdbc:rmi:jdbc:cloudscape:animalsurvey" );
    
         // PreparedStatement to add one to vote total for a
         // specific animal
         updateVotes =
            connection.prepareStatement(
               "UPDATE surveyresults SET votes = votes + 1 " +
               "WHERE id = ?"
            );

         updateVotes.setInt(1,value);
         ResultSet rs = pst.executeUpdate();
      // for any exception throw an UnavailableException to
      // indicate that the servlet is not currently available
      } //end try
      catch ( Exception exception ) 
     {
         debug.log(exception.getMessage());
         exception.printStackTrace();
         throw new UnavailableException( exception.getMessage() );
      }
//Any more SQL Statements should go here with the connection/statement/execute/GetResults
} //doPost

YMMV
Martin--
--------------------------------------------------------------------------- 
This e-mail message (including attachments, if any) is intended for the use of the individual
or entity to which it is addressed and may contain information that is privileged, proprietary
, confidential and exempt from disclosure. If you are not the intended recipient, you are
notified that any dissemination, distribution or copying of this communication is strictly
prohibited.
--------------------------------------------------------------------------- 
Le présent message électronique (y compris les pièces qui y sont annexées, le cas échéant)
s'adresse au destinataire indiqué et peut contenir des renseignements de caractère privé
ou confidentiel. Si vous n'êtes pas le destinataire de ce document, nous vous signalons qu'il
est strictement interdit de le diffuser, de le distribuer ou de le reproduire.
----- Original Message ----- 
From: "Mr. Steve Burrus" <burrus1@swbell.net>
To: <users@tomcat.apache.org>
Sent: Sunday, January 28, 2007 4:48 PM
Subject: Need Help w. Database Servlet.


> hi all. I find myself in need of help/assistance with a longtime problem 
> of mine and that is how do you get a servlet working with a backend 
> database server?? Here is the basic SurveyServlet.java servlet and 
> please notice that the database server in question is IBM's Cloudscape . 
> after the servlet I have the html file which the servlet is supposed to 
> work with. thanx in advance for anyone's help.
> 
> 
> import java.io.*;
> import java.text.*;
> import java.sql.*;
> import javax.servlet.*;
> import javax.servlet.http.*;
> 
> public class SurveyServlet extends HttpServlet {
>   private Connection connection;
>   private PreparedStatement updateVotes, totalVotes, results;
> 
>   // set up database connection and prepare SQL statements
>   public void init( ServletConfig config )
>      throws ServletException
>   {
>      // attempt database connection and create PreparedStatements
>      try {
>         Class.forName( "COM.cloudscape.core.RmiJdbcDriver" );
>         connection = DriverManager.getConnection(
>            "jdbc:rmi:jdbc:cloudscape:animalsurvey" );
> 
>         // PreparedStatement to add one to vote total for a
>         // specific animal
>         updateVotes =
>            connection.prepareStatement(
>               "UPDATE surveyresults SET votes = votes + 1 " +
>               "WHERE id = ?"
>            );
> 
>         // PreparedStatement to sum the votes
>         totalVotes =
>            connection.prepareStatement(
>               "SELECT sum( votes ) FROM surveyresults"
>            );
> 
>         // PreparedStatement to obtain surveyoption table's data
>         results =
>            connection.prepareStatement(
>               "SELECT surveyoption, votes, id " +
>               "FROM surveyresults ORDER BY id"
>            );
>      }
>      
>      // 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 of init method
> 
>   // 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();
>      DecimalFormat twoDigits = new DecimalFormat( "0.00" );
> 
>      // start XHTML document
>      out.println( "<?xml version = \"1.0\"?>" );
> 
>      out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
>         "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
>         "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
> 
>      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" ) );
> 
>      // attempt to process a vote and display current results
>      try {
> 
>         // update total for current survey response
>         updateVotes.setInt( 1, value );
>         updateVotes.executeUpdate();
> 
>         // get total of all survey responses
>         ResultSet totalRS = totalVotes.executeQuery();
>         totalRS.next();
>         int total = totalRS.getInt( 1 );
> 
>         // get results
>         ResultSet resultsRS = results.executeQuery();
>         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.print( twoDigits.format(
>               ( double ) votes / total * 100 ) );
>            out.print( "%  responses: " );
>            out.println( votes );
>         }
> 
>         resultsRS.close();
>         
>         out.print( "Total responses: " );
>         out.print( total );
>         
>         // end XHTML document
>         out.println( "</pre></body></html>" );         
>         out.close();
>      }
> 
>      // 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 of doPost method
> 
>   // close SQL statements and database when servlet terminates
>   public void destroy()
>   {
>      // attempt to close statements and database connection
>      try {
>         updateVotes.close();
>         totalVotes.close();
>         results.close();
>         connection.close();
>      }
> 
>      // handle database exceptions by returning error to client
>      catch( SQLException sqlException ) {
>         sqlException.printStackTrace();
>      }
>   }  // end of destroy method
> }
> 
> the html file :
> 
> <?xml version = "1.0"?>
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
>   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
> 
> <!--  Survey.html -->
> 
> <html xmlns = "http://www.w3.org/1999/xhtml">
> <head>
>   <title>Survey</title>
> </head>
> 
> <body>
> <form method = "post" action = "/animalsurvey">
> 
>   <p>What is your favorite pet?</p>
> 
>   <p>
>      <input type = "radio" name = "animal"
>         value = "1" />Dog<br />
>      <input type = "radio" name = "animal"
>         value = "2" />Cat<br />
>      <input type = "radio" name = "animal"
>         value = "3" />Bird<br />
>      <input type = "radio" name = "animal"
>         value = "4" />Snake<br />
>      <input type = "radio" name = "animal"
>         value = "5" checked = "checked" />None
>   </p>
> 
>   <p><input type = "submit" value = "Submit" /></p>
> 
> </form>
> </body>
> </html>
> 
> 
> 
> 
> 
> 
> ---------------------------------------------------------------------
> To start a new topic, e-mail: users@tomcat.apache.org
> To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
> For additional commands, e-mail: users-help@tomcat.apache.org
> 
>
Mime
View raw message