0

我有一个程序,可以通过问题和答案从 SQL DB 生成 2 个问题测试,这些问题是由问题 ID 随机选择的。我遇到的问题是,当从 net beans 正常运行时,问题实际上并没有在一个新系统上随机化,而这个新系统在它没有显示任何问题之前还没有运行。但是当它用断点调试时,它工作得很好。不久前我在另一个程序上发生了这样的事情,不知道我是如何修复它的,我相信这是缓存和数学随机之间的问题。

欢迎页面加载到 quizzical 控制器,该控制器在初始化时在 TestDA servlet 中生成测试

package org.citatscc.quiz.controller;

import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.citatscc.quiz.business.*;
import org.citatscc.quiz.business.TestTaker;
import org.citatscc.quiz.data.TestDA;


public class Quizzical extends HttpServlet {
    //the test will be available to all threads
    //eventually each TestTaker will store their Test in a Session
    private Test myQuiz=null;

    @Override
    public void init(){ 
       String testName = getServletConfig().getInitParameter("QuizName");
       //generate the basic Test which will be used to create each TestTaker's myQuiz
       myQuiz = TestDA.generateTest(testName);


    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       request.setAttribute("myQuiz", myQuiz);
       //here we are simply showing the test generated from the database
       String action = request.getParameter("action");
       String url = "/QuizView.jsp";
       if(action == null)
       {
           url = "/QuizMain.jsp";
       }
       else if(action.equals("AddTest"))
       {
           url = "/QuizAdd.jsp";
       }
       else if(action.equals("addNewTest"))
       {
           addNewTest(request);
       }



       RequestDispatcher dispatch = getServletContext().getRequestDispatcher(url);
       dispatch.forward(request, response);

    }

    public boolean addNewTest(HttpServletRequest request)
    {

        return false;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);

    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}

测试DA

package org.citatscc.quiz.data;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.citatscc.quiz.business.Question;
import org.citatscc.quiz.business.Test;

public class TestDA{

    public static Test generateTest(String testName) {

        List<Question> questions = new ArrayList<Question>();

       Test test = null;
       boolean sameNum = true;
       int randNum1 = 0;
       int randNum2 = 0;
       while(sameNum == true)
       {
           randNum1 = getRandomNumber();
           randNum2 = getRandomNumber();

           if(randNum1 == 0 || randNum2 == 0 || randNum1 > 7 || randNum2 > 7 ||
                   randNum1 == 6 || randNum2 == 6)
           {
               sameNum = true;
           }
           else
           {
                if(randNum1 != randNum2)
                {
                    sameNum = false;
                }
           }

       }

        String questionID1 = getQuestionID(randNum1);
        String questionID2 = getQuestionID(randNum2);
        try {
            String questionTxt1 = getQuestionStringByQID(questionID1);
            String questionTxt2 = getQuestionStringByQID(questionID2);
            questions.add(getAnswers(questionTxt1, questionID1));
            questions.add(getAnswers(questionTxt2, questionID2));
            test = new Test(testName,questions);
        } catch (Exception ex) {
            String message = ex.getMessage();
        }

        return test;
    }

    public static Question getAnswers(String questionTxt, String questionID) throws Exception
    {
        Connection connection = DBUtil.getConnection();
        Statement statement = connection.createStatement();

        int counter = 0;
        int correctAnswer = 0;
        ArrayList<String> answers = new ArrayList<String>();
        String preparedQuery = "SELECT * FROM `answers` WHERE `qID` = " + questionID;
        ResultSet resultSet = statement.executeQuery(preparedQuery);
        while (resultSet.next())
        {
            answers.add(resultSet.getString(2));
            if(resultSet.getInt(3) == 1)
            {
                correctAnswer = counter;
            }
            else
            {
                counter++;
            }
        }
        Question question = new Question(questionTxt, answers, correctAnswer);

        return question;
    }

    public static String getQuestionStringByQID(String qID) throws Exception
    {

        Connection connection = DBUtil.getConnection();
        Statement statement = connection.createStatement();

        String preparedQuery = "SELECT `question` FROM `questions` WHERE `qID` = " + qID;
        ResultSet resultSet = statement.executeQuery(preparedQuery);
        String questionText = "";
        while (resultSet.next())
        {
            questionText = resultSet.getString(1);
        }
        connection.close();
        return questionText;
    }



    public static int getRandomNumber()
    {
        Random rnd = new Random();
        int randomNum = rnd.nextInt(8);
        return randomNum;
    }

    public static String getQuestionID(int randNum)
    {
        int intqID = randNum * 111;
        String qID = "" + intqID;

        return qID;
    }

    public static void insertQuestion(String qID, String qText, List<String>qChoices, int correct)throws SQLException{
        String preparedQuestion = "INSERT INTO questions VALUES(?,?)";



    }

    public static void upDateQuestion(String qID, String qText, List<String>qChoices, int correct) throws SQLException{

    }
}

初始化完成后,它重定向到一个菜单 jsp,在点击一个测试链接后,它在重定向到 QuizView.jsp 之前点击了 quizzical 控制器

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
        <title>Quiz View</title>
        <%@taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

        <%@taglib  prefix="cit"  uri="/WEB-INF/tld/test.tld" %>
        <%@taglib  prefix="includes"  tagdir="/WEB-INF/tags/" %>

        <%@ page import="org.citatscc.quiz.business.Test, org.citatscc.quiz.business.Question" %>
        <%@ page import="java.util.*" %>
        <link href="quiz.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
    <div id="top"><includes:Header image="cit_logo.jpg" alt="cit logo image" tagline="${myQuiz.testName}"/></div>
    <div id="leftnav">

    </div>
    <div id="content">

        <form action="Quiz" method="post">
         <c:forEach var="question" items="${myQuiz.questionList}" varStatus="qCount">

             <h2>${qCount.count}.  ${question.questionText} </h2>
             <c:forEach var="choice" items="${question.choices}" varStatus="choiceCount" >
                 <!-- custom tag here -->
                 <cit:quiz_choiceButton groupName="choice${qCount.count}" text="${choice}" value="${choiceCount.index}" />
             </c:forEach>
             <br />
         </c:forEach>
        <input type="submit" name="done" value="Submit" />
        </form> 
    </div>
    <div id="footer"><includes:Footer /></div>
</div>

</body>
</html>

任何帮助表示赞赏。

4

1 回答 1

0

servlet 方法init()在 servlet 初始化期间调用一次。因此,您对所有以下请求都有相同的测试。

private Test myQuiz=null;

对于所有请求具有相同的值。

更多文档:http://docs.oracle.com/javaee/5/api/javax/servlet/Servlet.html#init(javax.servlet.ServletConfig)

于 2013-06-05T23:32:35.360 回答