quizservlet.java
来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 90 行
JAVA
90 行
package httpExamples;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;/** * Title: QuizServlet * Description: QuizServlet to process QuizForm.html * Copyright: Copyright (c) 2001 * Company: * @author Andrew Harbourne-Thomas * @version 1.0 */public class QuizServlet extends HttpServlet{ private static final String AUSTRALIA = "australia"; private static final String AUSTRALIA_CAPITAL = "Canberra"; private static final String BRAZIL = "brazil"; private static final String BRAZIL_CAPITAL = "Brasilia"; private static final String IRELAND = "ireland"; private static final String IRELAND_CAPITAL = "Dublin"; private static final String NAME = "name"; /**Process the HTTP Get request*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int count = 0; String name = request.getParameter(NAME); String answerAustralia = request.getParameter(AUSTRALIA); String answerBrazil = request.getParameter(BRAZIL); String answerIreland = request.getParameter(IRELAND); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>QuizServlet</title></head>"); out.println("<body>"); if (name != null && name.trim().length() > 0) { out.println("<h1>Welcome " + name + "</h1>"); } else { out.println("<h1>Welcome</h1>"); } count = count + doQuestion(out, 1, answerAustralia, AUSTRALIA_CAPITAL); count = count + doQuestion(out, 2, answerBrazil, BRAZIL_CAPITAL); count = count + doQuestion(out, 3, answerIreland, IRELAND_CAPITAL); out.println("<hr width=\"25%\" align=\"left\">"); out.println("You scored " + count + " out of 3"); String userAgent = request.getHeader("user-agent"); if (userAgent != null && userAgent.indexOf("MSIE") != -1) { out.println(" using Microsoft browser."); } else if (userAgent != null) { out.println(" using Non-Microsoft browser."); } out.println("</body></html>"); } /**Process the HTTP Post request the same as the Get request*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** Process the questions */ private int doQuestion(PrintWriter out, int number, String answer, String solution) { out.println("<h2>Question " + number + "</h2>"); if (answer != null && solution.equalsIgnoreCase(answer)) { out.println("<b>Correct</b>"); return 1; } else { out.println("<b>Wrong:</b> The correct answer is " + solution); return 0; } }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?