调用Servlet并从JavaScript调用Java代码以及参数 [英] Call Servlet and invoke Java code from JavaScript along with parameters
问题描述
我的会话密钥是我从REST API调用获得的JavaScript变量。我需要在servlet中调用我的Java代码并将该密钥作为参数传递。我可以用什么JavaScript函数来做?
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?
推荐答案
几种方式:
-
使用
window.location
来触发GET请求。警告是它是同步的(因此客户端将看到当前页面被更改)。
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.
无论哪种方式,键
都可以通过<$ c获得$ c> 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
这篇关于调用Servlet并从JavaScript调用Java代码以及参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!