2015-10-21 94 views
1

我寫了下面的方法。我可以提醒mycode。如何將mycode值設置爲HttpServletResponse。如何在一個servlet中獲得java腳本值到java

public void postContent(HttpServletRequest request, HttpServletResponse response) 
     throws IOException { 
    response.setContentType("text/html"); 
    PrintWriter out = null; 
    try { 
     out.println("<title>SMS OTP</title>" + 
       "<body bgcolor=FFFFFF>"); 
     out.println("<h2>Enter your code</h2><br/>"); 
     out.println("<script language=\"JavaScript\">function getCode(form){mycode = form.code.value;alert(mycode);}</script>"); 

     out.println("<form method='POST'>"); 
     out.println("<input type='text' name='code' id='code'/>&nbsp;<input type='button' onclick='getCode(this.form)' value='Submit'/>"); 
     out.println("</form>"); 
     out.println("</body"); 

     out.close(); 
     if (log.isDebugEnabled()) { 
      log.debug("The code is successfully displayed."); 
     } 
    } catch (IOException e) { 
     log.error("Unable to show the code"); 
    } 
} 

回答

0

你並不真的需要javascript,表單值在提交時傳遞給servlet。請注意,JavaScript是在瀏覽器上執行的,只有將它們發送到服務器(到java servlet)的方式是將它們發佈到新的HTTP請求中,無論是AJAX還是表單提交。這意味着在您的情況下,代碼僅在提交後可用於java方法。

在這種情況下,你可能只需要刪除你的JavaScript,通過與

out.println("<form method='POST'>"); 
out.println("<input type='text' name='code' id='code'/>&nbsp;<input type='submit' value='Submit'/>"); 

更換

out.println("<script language=\"JavaScript\">function getCode(form){mycode = form.code.value;alert(mycode);}</script>"); 
out.println("<form method='POST'>"); 
out.println("<input type='text' name='code' id='code'/>&nbsp;<input type='button' onclick='getCode(this.form)' value='Submit'/>"); 

,並在你的Java方法,只是做

String code = request.getParameter("code"); 

但你的java方法必須是是處理傳入表單的那個su bmit。