2015-10-21 55 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。