简体   繁体   中英

how to get java script value to java in a servlet

I have written the following method. I'm able to alert mycode. How can I set the mycode value into 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. 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. This means in your case that the code is only available to the java method after the submit.

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

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

But your java method must be the one handling the incoming form submit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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