调用 Servlet 并从 JavaScript 调用 Java 代码以及参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2132242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:53:15  来源:igfitidea点击:

Call Servlet and invoke Java code from JavaScript along with parameters

javascriptjspservletsparameter-passing

提问by Pranav

I have session key that is a JavaScript variable which I got from a REST API call. I need to call my Java code in a servlet and pass that key as a parameter. What JavaScript function can I use to do that?

我有会话密钥,它是我从 REST API 调用中获得的 JavaScript 变量。我需要在 servlet 中调用我的 Java 代码并将该键作为参数传递。我可以使用什么 JavaScript 函数来做到这一点?

回答by BalusC

Several ways:

几种方式:

  1. Use window.locationto fire a GET request. Caveat is that it"s synchronous (so the client will see the current page being changed).

    window.location = "http://example.com/servlet?key=" + encodeURIComponent(key);
    

    Note the importance of built-in encodeURIComponent()function to encode the request parameters before passing it.

  2. Use form.submit()to fire a GET or POST request. The caveat is also that it"s synchronous.

    document.formname.key.value = key;
    document.formname.submit();
    

    With

    <form name="formname" action="servlet" method="post">
        <input type="hidden" name="key">
    </form>
    

    Alternatively you can also only set the hidden field of an existing form and just wait until the user submits it.

  3. Use XMLHttpRequest#send()to fire an asynchronous request in the background (also known as Ajax). Below example will invoke servlet"s doGet().

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://example.com/servlet?key=" + encodeURIComponent(key));
    xhr.send(null);
    

    Below example will invoke servlet"s doPost().

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://example.com/servlet");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("key=" + encodeURIComponent(key));
    
  4. Use jQueryto send a crossbrowser compatible Ajax request (above xhrcode works in real browsers only, for MSIE compatibility, you"ll need to add some clutter ;) ).

    $.get("http://example.com/servlet", { "key": key });
    

    $.post("http://example.com/servlet", { "key": key });
    

    Note that jQuery already transparently encodes the request parameters all by itself, so you don"t need encodeURIComponent()here.

  1. 使用window.location火的GET请求。需要注意的是它是同步的(因此客户端将看到当前页面正在更改)。

    window.location = "http://example.com/servlet?key=" + encodeURIComponent(key);
    

    请注意内置encodeURIComponent()函数在传递请求参数之前对其进行编码的重要性。

  2. form.submit()火GET或POST请求。需要注意的是,它也是同步的。

    document.formname.key.value = key;
    document.formname.submit();
    

    <form name="formname" action="servlet" method="post">
        <input type="hidden" name="key">
    </form>
    

    或者,您也可以只设置现有表单的隐藏字段,然后等待用户提交。

  3. 用于XMLHttpRequest#send()在后台触发异步请求(也称为 Ajax)。下面的示例将调用 servlet"s doGet()

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://example.com/servlet?key=" + encodeURIComponent(key));
    xhr.send(null);
    

    下面的示例将调用 servlet"s doPost()

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://example.com/servlet");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("key=" + encodeURIComponent(key));
    
  4. 使用jQuery发送与跨xhr浏览器兼容的 Ajax 请求(以上代码仅适用于真实浏览器,为了兼容 MSIE,您需要添加一些混乱 ;) )。

    $.get("http://example.com/servlet", { "key": key });
    

    $.post("http://example.com/servlet", { "key": key });
    

    请注意,jQuery 已经完全透明地对请求参数进行了编码,因此您不需要encodeURIComponent()这里。

Either way, the keywill be just available by request.getParameter("key")in the servlet.

无论哪种方式,key都只能request.getParameter("key")在 servlet 中使用。

See also:

也可以看看:

回答by Quentin

No JavaScript function per se, but browsers usually* provide an XMLHttpRequestobject and you can go through that.

本身没有 JavaScript 函数,但浏览器通常*提供一个XMLHttpRequest对象,您可以通过它

Librariessuch as YUIand jQueryprovide helper functions to simplify its usage.

YUIjQuery提供了帮助函数来简化其使用。

* for a value of "usually" that includes pretty much any browser that supports JavaScript and was released since Netscape 4 died

* 表示“通常”的值,包括几乎所有支持 JavaScript 且自 Netscape 4 死后发布的浏览器

回答by SoSen

When sending POST add header xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

发送 POST 时添加头 xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

The code looks like Client:

代码看起来像 客户端:

    function executeRequest(req) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
               // Typical action to be performed when the document is ready:
               document.getElementById("response").value = xhttp.responseText;
            }
        };
        xhttp.open("POST", "execute/cardbrowser", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("lorem=ipsum&name=binny");
    }

Server:

服务器:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println(req.getParameter("lorem"));
}