javawed程序编写一个页面输出单选试题
时间: 2024-03-01 14:54:23 浏览: 88
用JavaScript脚本语言编写试题网页.pdf
好的,我可以为您提供一个简单的 Java Web 程序,用于输出单选试题的页面。以下是示例代码:
```java
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 SingleChoiceQuestionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String question = "1. What is the capital city of France?";
private final String[] options = {"A. London", "B. Paris", "C. Madrid", "D. Berlin"};
private final String answer = "B";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Single Choice Question</title>");
out.println("</head>");
out.println("<body>");
out.println("<form action=\"SingleChoiceQuestionServlet\" method=\"post\">");
out.println("<p>" + question + "</p>");
for (String option : options) {
out.println("<p><input type=\"radio\" name=\"answer\" value=\"" + option.charAt(2) + "\">" + option + "</p>");
}
out.println("<input type=\"submit\" value=\"Submit\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String selectedAnswer = request.getParameter("answer");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Single Choice Question</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Result:</h1>");
if (selectedAnswer != null && selectedAnswer.equals(answer)) {
out.println("<p>Your answer is correct!</p>");
} else {
out.println("<p>Your answer is incorrect. The correct answer is " + answer + ".</p>");
}
out.println("</body>");
out.println("</html>");
}
}
```
这个程序定义了一个 `SingleChoiceQuestionServlet` 类,继承自 `HttpServlet`,用于处理 HTTP 请求。在 `doGet` 方法中,它生成一个包含试题和选项的 HTML 表单,用户可以在这个表单中选择答案,并提交到 `doPost` 方法中进行处理。在 `doPost` 方法中,它获取用户选择的答案,并与正确答案进行比较,输出用户的得分。
您可以将这个程序编译成一个 WAR 文件,然后将它部署到一个 Java Web 服务器上,如 Tomcat 或 Jetty。当用户访问这个程序的 URL 时,它就会输出单选试题的页面。
阅读全文