标准化考试示例java servlet实现

一个简单的标准化考试系统。采用Eclipse3.2+MyEclipse5.0 开发。在tomcat 5.5下运行正常。
一共分为3个页面。文件选择,考试,显示成绩。
DefaultPage.java
[codes=java]
package idv.dean;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DefaultPage extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String t2=”

“+
       ““+
         ““+
         “
“;
    response.setContentType(“text/html”);
    response.setCharacterEncoding(“gb2312”);
    PrintWriter out = response.getWriter();
    out
        .println(““);
    out.println(““);
    out.println(”  Select Test File“);
    out.println(”  “);
    out.println(” 请选择要考试的文件:
“);
    out.print(t2);    
    out.println(”  “);
    out.println(““);
    out.flush();
    out.close();
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request,response);
    
  }

}

[/codes]

Exam.java
[codes=java]
package idv.dean;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Exam extends HttpServlet {
  String filename = “”, correctAnswer = “”, selection = “”;

  int nA = 0;

  // 试题数组.每个试题存入字符串数组中
  String[] quest;

  public String checkMethod(HttpServletRequest theRequest) {
    return theRequest.getMethod();
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 当直接输入此页面地址转到首页
    String loginUrl = “DefaultPage”;
    response.sendRedirect(loginUrl);

  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 新建一session对象
    HttpSession session = request.getSession(true);
    // 获取选择文件名
    String ss = request.getParameter(“filename”);
    System.out.println(ss);
    // 打开文件
    correctAnswer = getCorrectAnswer(ss);
    nA = correctAnswer.toCharArray().length;
    // 读取文件内容
    quest = getTestContent(ss);
    response.setContentType(“text/html”);
    response.setCharacterEncoding(“gb2312”);
    PrintWriter out = response.getWriter();
    out
        .println(““);
    out.println(““);
    out.println(”  Exam“);
    out.println(”  “);
    out.println(“

欢迎参加考试

“);
    out.println(“当前选择文件为:” + ss);
    out.println(“
试题数:” + nA + “
“);
    out.println(“

“);
    // 循环显示每到试题
    for (int n = 0; n < nA; n++) {
      // 显示试题
      out.println(quest[n]);
      // 为试题添加单选框
      out.println(radioSelect(n));
    }
    // 将获得的正确答案和试题数做session属性
    setCorrectAnsToSession(session);
    session.setAttribute(“nA”, nA);
    out.println(“
 ” + “

“);
    out.println(”  “);
    out.println(““);
    out.flush();
    out.close();
  }

  public String getCorrectAnswer(String fName)

  {
    String correctAns = null;
    // filename = fName;
    try {
      // 读取当前工程文件夹下的文件
      File f = new File(getServletContext().getRealPath(“/”) + fName);
      FileReader in = new FileReader(f);
      BufferedReader buffer = new BufferedReader(in);
      // 去除前后空格后将答案存入correctAnswer中
      correctAns = (buffer.readLine()).trim();
      // 根据答案数获得试题数量
      // nA=correctAns.toCharArray().length;
      in.close();
      buffer.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return correctAns;
  }

  public String[] getTestContent(String fName) {
    String[] testContent = new String[nA];
    int n = -1;
    try {

      File f = new File(getServletContext().getRealPath(“/”) + fName);
      FileReader in = new FileReader(f);
      BufferedReader buffer = new BufferedReader(in);
      String s = null;
      StringBuffer temp = new StringBuffer();
      if (buffer != null) {// 跳过第一行答案
        s = buffer.readLine();
        while ((s = buffer.readLine()) != null) { // 如果以**开头
          if (s.startsWith(“**”)) {
            // 试题编号加1
            n++;
            // 清空字符串缓存
            temp = new StringBuffer();
          } else {
            // 将当前行附加到temp后.并加html换行标识
            temp.append(s + “
“);
            // 以endend结尾关闭文件
            if (s.startsWith(“endend”)) {
              break;
            }
            // 将获得试题存入试题数组
            testContent[n] = new String(temp);
          }
        }
      } else {

      }
      in.close();
      buffer.close();
    } catch (Exception e) {
      e.printStackTrace();

    }
    return testContent;

  }

  /**
   * 显示单选框
   *
   * @param n
   *            单选编号
   * @return 单选html代码
   */
  public String radioSelect(int n) {
    String temp = “        + “\” value=\”A\”/>A” + “        + “\” value=\”B\”/>B” + “        + “\” value=\”C\”/>C” + “        + “\” value=\”D\”/>D” + “        + “\” value=\”E\”/>E
“;
    return temp;
  }

  protected void setCorrectAnsToSession(HttpSession session) {
    session.setAttribute(“correctAnswer”, correctAnswer);
  }

}

[/codes]
Score.java
[codes=java]
package idv.dean;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Score extends HttpServlet {
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 获得session
    HttpSession session = request.getSession();
    String loginUrl = “DefaultPage”;
    response.setContentType(“text/html”);
    int nA = 0;
    String correctAnswer = null;

    if (session == null)
      response.sendRedirect(loginUrl);
    else {

      // 取得正确答案
      correctAnswer = (String) session.getAttribute(“correctAnswer”);

    }
    nA = correctAnswer.toCharArray().length;

    // 定义一字符数组存放所选答案
    char[] ansArray = new char[nA];
    // 初始化答案全为z,避免出现空选项;
    for (int i = 0; i < nA; i++) {
      ansArray[i] = ‘z’;
    }
    PrintWriter out = response.getWriter();
    out
        .println(““);
    out.println(““);
    out.println(”  show score“);
    out.println(”  “);
    out.println(“the correct answer is :” + correctAnswer);
    // 获得正确答案
    // String correctAnswer=request.getParameter(“correctAnswer”);
    // 枚举所有参数
    String myAns = new String(getAns(request, nA));
    int score = getScore(correctAnswer, myAns);
    // out.println(myAns);
    out.print(“
Your answer is:” + myAns);
    out.print(“
your score is:”);
    out.println(score);
    out.println(”  “);
    out.println(““);
    out.flush();
    out.close();

  }

  protected int getScore(String correctAnswer, String myAnswer) {
    int m = correctAnswer.length();
    int score = 0;
    for (int n = 0; n < m; n++) {
      try {
        if (myAnswer.charAt(n) == correctAnswer.charAt(n)) {
          score++;

        }
      } catch (StringIndexOutOfBoundsException e) {
        n = 0;
      }
    }
    return score;
  }

  protected char[] getAns(HttpServletRequest request, int nSize) {
    Enumeration paramNames = request.getParameterNames();
    char[] ansArrays = new char[nSize];
    while (paramNames.hasMoreElements()) {
      String paramName = (String) paramNames.nextElement();
      // 如果参数是以ans开头的单选答案
      if (paramName.startsWith(“ans”)) {
        // 获取选择项
        String[] paramValues = request.getParameterValues(paramName);
        // 如果所选不为空
        if (paramValues.length == 1) {
          // 获得所选项的值
          String paramValue = paramValues[0].toLowerCase();
          StringBuffer str = new StringBuffer();
          // 获得题号
          str.append(paramName.charAt(3));
          String ansPos = new String(str);
          // 根据题号重组答案顺序
          ansArrays[Integer.parseInt(ansPos)] = paramValue.charAt(0);

        }
      }
    }
    return ansArrays;
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 当直接输入此页面地址转到首页
    String loginUrl = “DefaultPage”;
    response.sendRedirect(loginUrl);
  }

}

[/codes]
tomcat部署文件。放到webapps文件夹下即可
[sfile]attachment/stdtest.rar[/sfile]
servlet源文件
[sfile]attachment/src.rar[/sfile]

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据