2013-04-11 50 views
0

我開始學習servlet,我正在使用MySQL和Tomcat。我試圖做一個簡單的servlet,當點擊提交按鈕時,它將通過再次調用doGet()函數顯示一組不同的指令,並將光標移動到下一組。帶有Tomcat的HTTP servlet

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()函數被再次調用。

回答

1

首先你需要存儲一些東西,讓你知道你在列表中的位置。因此,例如,添加一個隱藏的表單字段,它可以讓您從數據庫中讀取正確的東西。我會假設你在db中的記錄是編號的。

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=\"\">"); 
+1

我修改了一下代碼,它工作 – user1832478 2013-04-12 21:34:07

0

如何用一個while循環替換if語句來遍歷數據庫中的所有記錄,然後可以使用相同的代碼將其打印到網頁。

您可能還想了解如何使用使控制器(servlet)和視圖(呈現給用戶的網頁或JSP)分離的JSP。