Pranav Pranav - 1 year ago 116
Javascript Question

Call Servlet and invoke Java code from JavaScript along with parameters

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?

Answer Source

Several ways:

  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 = '' + 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;


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

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

    var xhr = new XMLHttpRequest();'GET', '' + encodeURIComponent(key), true);
  4. 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('', { 'key': key });

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

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.

See also:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download