I have session key that is a javascript variable which i get from a Rest api call. I need to call a servlet and pass that key as a parameter. What Javascript function can I use to do that?
No JavaScript function per se, but browsers usually* provide an XMLHttpRequest object and you can go through that.
Libraries such as YUI and jQuery provide helper functions to simplify its usage.
* for a value of "usually" that includes pretty much any browser that supports JavaScript and was released since Netscape 4 died
Several ways:
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=' + key;
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.
Use
XMLHttpRequest#send()
to fire an asynchronous request in the background (also known as Ajax).var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/servlet?key=' + key, true); xhr.send(null);
Use jQuery to send a crossbrowser compatible Ajax request (above works in real browsers only, for MSIE compatibility, you'll need to add some clutter ;) ).
$.get('http://example.com/servlet?key=' + key);
Either way, the key
will be just available by request.getParameter("key")
in the servlet. To learn more about communication between Java/JSP and JavaScript, you may find this article useful as well.