2013-04-11 6 views
0

서블릿을 배우기 시작했고 MySQL과 Tomcat을 사용하고 있습니다. 제출 버튼을 클릭하면 doGet() 함수를 다시 호출하여 다른 명령어 세트를 표시하고 커서를 다음 세트로 이동시키는 간단한 서블릿을 만들려고합니다.Tomcat이있는 HTTP 서블릿

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의 기록에 번호가 매겨 졌다고 가정합니다. 그런 다음 하나 알아

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 

:

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

는 그런 다음 서버가 요청을 얻을 때 그 값을 수집하고 다음 값을 읽고 그것을 사용할 필요가

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

코드를 약간 수정하여 효과적입니다. – user1832478

0

if 문을 데이터베이스의 모든 레코드를 반복하는 데 while 루프를 사용하여 대체 한 다음 동일한 코드를 사용하여 웹 페이지에 인쇄 할 수 있습니다.

컨트롤러 (서블릿)와보기 (사용자에게 제공되는 웹 페이지 또는 JSP)를 구분하는 JSP 사용법을 배우고 싶을 수도 있습니다.

관련 문제