⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tiptestservlet.java

📁 高级java2 大学教程(含源码,经典的Java学习教程
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
// TipTestServlet.java
// TipTestServlet sends Tip Test to clients.
package com.deitel.advjhtp1.wireless;

// Java core packages
import java.io.*;
import java.sql.*;
import java.util.*;

// Java extension packages
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

// import third-party packages
import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class TipTestServlet extends HttpServlet {

   private Connection connection; // database connection

   private DocumentBuilderFactory factory;
   private TransformerFactory transformerFactory;

   // initialize servlet
   public void init() throws ServletException
   {
      // load database driver and instantiate XML factories
      try {

         // get JDBC driver from servlet container
         String jdbcDriver = 
            getServletConfig().getInitParameter( 
               "JDBC_DRIVER" );

         Class.forName( jdbcDriver ); // load JDBC driver

         // get database URL from servlet container
         String databaseUrl = 
            getServletConfig().getInitParameter( 
               "DATABASE_URL" );

         connection = DriverManager.getConnection( databaseUrl );

         // create a Factory to build XML Documents
         factory = DocumentBuilderFactory.newInstance();

         // create new TransformerFactory
         transformerFactory = TransformerFactory.newInstance();

      } // end try

      // handle exception database driver class does not exist
      catch ( ClassNotFoundException classNotFoundException ) {
         classNotFoundException.printStackTrace();
      }

      // handle exception in making Connection
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }

   } // end method init

   // respond to get requests
   protected void doGet( HttpServletRequest request,
      HttpServletResponse response )
      throws ServletException, IOException
   {
      // get Statement from database, then send Tip-Test Question
      try {

         // SQL query to database
         Statement statement = connection.createStatement();

         // get database information using SQL query
         ResultSet resultSet = 
            statement.executeQuery( "SELECT * FROM tipInfo" );

         // parse and send ResultSet to client
         if ( resultSet != null ) {

            // ensure that client does not cache questions
            response.setHeader( "Cache-Control", 
               "no-cache, must-revalidate" );
            response.setHeader( "Pragma", "no-cache" );

            sendTipTestQuestion( request, response, resultSet );
         }

         statement.close(); // close Statement
      }

      // handle exception in exectuting Statement
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      }

   } // end method doGet

   // respond to post requests
   protected void doPost( HttpServletRequest request,
      HttpServletResponse response )
      throws ServletException, IOException
   {
      // send ResultSet to appropriate client
      try {

         // determine User-Agent header
         String userAgent = request.getHeader( "User-Agent" );

         // if Internet Explorer is requesting client
         if ( userAgent.indexOf(
            ClientUserAgentHeaders.IE ) != -1 ) {

            Document document = 
               createXMLTipTestAnswer( request );

            // set appropriate Content-Type for client
            response.setContentType( "text/html" );

            // send XML content to client after XSLT
            applyXSLT( "XHTML/XHTMLTipAnswer.xsl", document, 
               response );
         }

         // if WAP client is requesting client
         else if ( userAgent.indexOf(
            ClientUserAgentHeaders.WAP ) != -1 ) {

            Document document = 
               createXMLTipTestAnswer( request );

            // set appropriate Content-Type for client
            response.setContentType( "text/vnd.wap.wml" );

            // send XML content to client after XSLT
            applyXSLT( "WAP/WAPTipAnswer.xsl", document, 
               response );
         }

         // if i-mode client is requesting client
         else if ( userAgent.indexOf(
            ClientUserAgentHeaders.IMODE ) != -1 ) {

            Document document = 
               createXMLTipTestAnswer( request );

            // set appropriate Content-Type for client
            response.setContentType( "text/html" );

            // send XML content to client after XSLT
            applyXSLT( "iMode/IMODETipAnswer.xsl", document, 
               response );
         }

         // if J2ME client is requesting client
         else if ( userAgent.indexOf(
            ClientUserAgentHeaders.J2ME ) != -1 )
            sendJ2MEAnswer( request, response );

      } // end try

      // handle exception if Document is null
      catch ( NullPointerException nullPointerException ) {
         nullPointerException.printStackTrace();
      }

   } // end method doPost

   // send Tip-Test data to client
   private void sendTipTestQuestion( 
      HttpServletRequest request, HttpServletResponse response, 
      ResultSet resultSet ) throws IOException
   {
      // send ResultSet to appropriate client
      try {

         // determine User-Agent header
         String userAgent = request.getHeader( "User-Agent" );

         // if Internet Explorer is requesting client
         if ( userAgent.indexOf(
            ClientUserAgentHeaders.IE ) != -1 ) {

            Document document = 
               createXMLTipTestQuestion( resultSet, request, 
                  request.getContextPath() + "/XHTML/images/", 
                     ".gif" );

            // set appropriate Content-Type for client
            response.setContentType( "text/html" );
            applyXSLT( "XHTML/XHTMLTipQuestion.xsl", document, 
               response );
         }

         // if WAP client is requesting client
         else if ( userAgent.indexOf(
            ClientUserAgentHeaders.WAP ) != -1 ) {

            Document document = 
               createXMLTipTestQuestion( resultSet, request,
                  request.getContextPath() + "/WAP/images/", 
                     ".wbmp" );

            // set appropriate Content-Type for client
            response.setContentType( "text/vnd.wap.wml" );
            applyXSLT( "WAP/WAPTipQuestion.xsl", document, 
               response );
         }

         // if i-mode client is requesting client
         else if ( userAgent.indexOf(
            ClientUserAgentHeaders.IMODE ) != -1 ) {

            Document document = 
               createXMLTipTestQuestion( resultSet, request,
                  request.getContextPath() + "/iMode/images/", 
                     ".gif" );

            // set appropriate Content-Type for client
            response.setContentType( "text/html" );
            applyXSLT( "iMode/IMODETipQuestion.xsl", document, 
               response );
         }

         // if J2ME client is requesting client
         else if ( userAgent.indexOf(
            ClientUserAgentHeaders.J2ME ) != -1 )
            sendJ2MEClientResponse( resultSet, request, 
               response );

      } // end try

      // handle exception if Document is null
      catch ( NullPointerException nullPointerException ) {
         nullPointerException.printStackTrace();
      }

   } // end method sendTipTestQuestion

   // send tip test to Internet Explorer client
   private Document createXMLTipTestQuestion( 
      ResultSet resultSet, HttpServletRequest request,
      String imagePrefix, String imageSuffix )
      throws IOException
   {
      // convert ResultSet to two-dimensional String array
      String resultTable[][] = getResultTable( resultSet );

      // create random-number generator
      Random random = new Random( System.currentTimeMillis() );

      // create 4 random tips
      int randomRow[] = getRandomIndices( random );

      // randomly determine correct index from 4 random indices
      int correctAnswer = Math.abs( random.nextInt() ) % 
         randomRow.length;

      int correctRow = randomRow[ correctAnswer ];

      // open new session
      HttpSession session = request.getSession();

      // store correct answer in session
      session.setAttribute( "correctAnswer", 
         new Integer( correctAnswer ) );

      // store correct tip name
      session.setAttribute( "correctTipName", new String( 
         resultTable[ correctRow ][ 1 ] ) );

      // store correct tip description
      session.setAttribute( "correctTipDescription", new String( 
         resultTable[ correctRow ][ 2 ] ) );

      // determine image to send client
      String imageName = imagePrefix  + 
         resultTable[ correctRow ][ 3 ] + imageSuffix;

      // create XML document based on randomly determined info
      try {

         // create document
         DocumentBuilder builder = factory.newDocumentBuilder();
         Document document = builder.newDocument();

         // create question root Element
         Element root = document.createElement( "question" );
         document.appendChild( root );

         // append Element image, which references image name
         Element image = document.createElement( "image" );
         image.appendChild( 
            document.createTextNode( imageName ) );
         root.appendChild( image );

         // create choices Element to hold 4 choice Elements
         Element choices = document.createElement( "choices" );

         // append 4 choice Elements that represent user choices
         for ( int i = 0; i < randomRow.length; i++ )
         {
            // determine choice Elements from resultTable
            Element choice = document.createElement( "choice" );
            choice.appendChild( document.createTextNode( 
               resultTable[ randomRow[ i ] ][ 4 ] ) );

            // set choice Element as correct or incorrect
            Attr attribute = 
               document.createAttribute( "correct" );

            if ( i == correctAnswer )
               attribute.setValue( "true" );
            else
               attribute.setValue( "false" );

            // append choice Element to choices Element
            choice.setAttributeNode( attribute );
            choices.appendChild( choice );
         }

         root.appendChild( choices );

         return document;

      } // end try

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -