最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jsp - Call Servlet and invoke Java code from JavaScript along with parameters - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Aug 7, 2016 at 6:47 BalusC 1.1m376 gold badges3.6k silver badges3.6k bronze badges asked Jan 25, 2010 at 12:40 PranavPranav 3,3128 gold badges38 silver badges52 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

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 = "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 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 });
    

    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.

See also:

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

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

When sending POST add header 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"));
}
发布评论

评论列表(0)

  1. 暂无评论