开发者

Invoking servlet after javascript function kills session

I had the following:

<a href="/servlet/MyServlet" onclick="javascript:CreatePageView();"> Link 1 </a>

but I noticed that the javascript function CreatePageView() did not get executed all the time and was creating a race situation. Sometimes the javascript would get executed, others times the redirect was happening first.

So I wanted to control the order of events and thought to invoke the servlet within my javascript function.

function CreatePageView()
{
    //Execute javascript function here

    //Invoke servlet here
    document.forms[0].action = "/servlet/MyServlet";
    document.forms[0].submit();
}

When I invoke my servlet, my session gets destroyed and I get redirected to the login page. Can anyone explain why this is happening? Or perhaps suggest an alternate method of invoking the servlet without killing the sess开发者_运维知识库ion? Thanks in advance.


This sounds much like as if that JavaScript is firing an asynchronous request. Otherwise the problem doesn't make any sense. The link's action will in any way only be executed when the JavaScript function has returned. But when you're firing an asynchronous/ajaxical request in the JS function, then indeed a race condition may occur. It namely doesn't execute in sync. It executes "in the background".

You need to ensure that the link is only invoked when the asynchronous request is finished. Assuming that you're doing it in "plain vanilla" JS by XMLHttpRequest instead of a convenient Ajaxical JS library like jQuery, then you need to do the job in the onreadystatechange.

Change the link as follows:

<a href="/servlets/MyServlet" onclick="return createPageView(this)">

(note that the javascript: pseudoprotocol is unnecessary and that JS functions usually start with lowercase)

And fix your JS function as follows (not MSIE compatible, fix that yourself)

function createPageView(link) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            window.location = link.href; // See?
        }
    }
    xhr.open('GET', 'http://example.com', true);
    xhr.send(null);
    return false; // Block link's default action.
}

As to the question why the session get destroyed, it will be "destroyed" when the request headers doesn't contain the proper session cookie, or when you call session.invalidate() in server side, or when the request is been fired on a different domain/context. You're the only one who can investigate which one is the culprit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜