【问题标题】:HTTP servlet with Tomcat带有 Tomcat 的 HTTP servlet
【发布时间】:2013-04-11 20:56:16
【问题描述】:

我开始学习 servlet,我正在使用 MySQL 和 Tomcat。我正在尝试制作一个简单的 servlet,当单击提交按钮时,它将通过再次调用 doGet() 函数来显示一组不同的指令并将光标移动到下一组。

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
{         
    out.println("<HTML><HEAD><TITLE>Instructions</TITLE><HEAD>");
    out.println("<BODY>");

    ResultSet rs = stmt.executeQuery("SELECT InstructNo, Instruct FROM Intructions");

    if(rs.next())
    {
        out.println(rs.getString("InstructNo") + ". " + rs.getString("Instruct"));
    }

    out.println("<form method=\"get\" action=\"\">");
    out.println("<input type=\"radio\" name=\"ans\" value=\"true\">True<br>");
    out.println("<input type=\"radio\" name=\"ans\" value=\"true\">False<br>");
    out.println("<input type=\"submit\" value=\"Submit\">");
    out.println("</BODY></HTML>");

单击提交按钮时,我不知道如何将光标移动到下一组 再次调用doGet() 函数。

【问题讨论】:

    标签: mysql tomcat servlets


    【解决方案1】:

    首先,您需要存储一些可以让您知道您在列表中的位置的内容。因此,例如,添加一个具有某种值的隐藏表单字段,使您可以从数据库中读取正确的内容。我假设您在数据库中的记录已编号。

      out.println("<input type=\"radio\" name=\"ans\" value=\"true\">False<br>");
      out.println("<input type='hidden' name='index' value='" + index + "' />");
      out.println("<input type=\"submit\" value=\"Submit\">");
    

    那么你需要在服务器收到请求时收集那个值,并用它来读取下一个值:

     String index = req.getParameter("index");
     int idx = Integer.parseInt(index); // add code to detect an exception here
     ResultSet rs = stmt.executeQuery("SELECT InstructNo, Instruct FROM Intructions where Index=" + index); // Check my rusty SQL here
    

    然后找出下一个:

    index = "" + (idx+1); // The +1 means to get the next one next time
    out.println("<form method=\"get\" action=\"\">");
    

    【讨论】:

      【解决方案2】:

      如果用一个while循环替换if语句来遍历数据库中的所有记录,然后你可以使用相同的代码将它打印到网页上。

      您可能还想了解如何使用 JSP,它将控制器(servlet)和视图(呈现给用户的网页;或 JSP)分开。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-27
        • 2014-07-23
        • 2015-03-23
        • 1970-01-01
        • 2015-06-28
        • 2012-01-05
        • 2020-11-19
        • 1970-01-01
        相关资源
        最近更新 更多