且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 14:15:22

几种方式:


  1. 使用 window.location 来触发GET请求。警告是它是同步的(因此客户端将看到当前页面被更改)。

  1. Use window.location to 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);

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

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

使用 form.submit()发出GET或POST请求。需要注意的是它是同步的。

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();

使用

<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.

使用 XMLHttpRequest#send()在后台触发异步请求(也称为阿贾克斯)。下面的示例将调用servlets doGet()

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

下面的例子将调用servlets doPost()

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


  • 使用 jQuery 发送一个与浏览器兼容的Ajax请求(上面的 xhr 代码仅适用于实际浏览器,对于MSIE兼容性,你需要添加一些杂乱的内容;))。

  • Use jQuery to send a crossbrowser compatible Ajax request (above xhr code 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 });
    

    请注意,jQuery已经透明地对请求参数进行了透明编码,所以你不需要 encodeURIComponent()

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

    无论哪种方式,都可以通过 servlet中的request.getParameter(key)。

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

    • How to use Servlets and Ajax?
    • Access Java / Servlet / JSP / JSTL / EL variables in JavaScript