简体   繁体   English

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

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

I have written the following method. 我写了下面的方法。 I'm able to alert mycode. 我能够提醒mycode。 How can I set the mycode value into HttpServletResponse. 如何将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");
    }
}

You don't really need javascript here, form values are passed to servlet on submit. 您这里实际上并不需要JavaScript,而是在提交时将表单值传递给servlet。 Note that javascript is executed on the browser, and only way of getting them to server (to java servlet) is to post them in a new HTTP request, be it AJAX or form submit. 请注意,javascript是在浏览器上执行的,将它们发送到服务器(到达Java servlet)的唯一方法是将它们发布到新的HTTP请求中,无论是AJAX还是表单提交。 This means in your case that the code is only available to the java method after the submit. 这意味着在您的情况下,代码仅在提交后可用于java方法。

In this case you can probably just remove your javascript, by replacing 在这种情况下,您可以替换为

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'/>");

with

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

and in your java method, just do 在你的java方法中

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

But your java method must be the one handling the incoming form submit. 但是您的java方法必须是处理传入表单提交的方法。

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

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