繁体   English   中英

如何在Servlet中将Java脚本值获取到Java

[英]how to get java script value to java in a servlet

我写了下面的方法。 我能够提醒mycode。 如何将mycode值设置到HttpServletResponse中。

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

您这里实际上并不需要JavaScript,而是在提交时将表单值传递给servlet。 请注意,javascript是在浏览器上执行的,将它们发送到服务器(到达Java servlet)的唯一方法是将它们发布到新的HTTP请求中,无论是AJAX还是表单提交。 这意味着在您的情况下,代码仅在提交后可用于java方法。

在这种情况下,您可以替换为

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 method='POST'>");
out.println("<input type='text' name='code' id='code'/>&nbsp;<input type='submit' value='Submit'/>");

在你的java方法中

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

但是您的java方法必须是处理传入表单提交的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM