abhijitsinghh
abhijitsinghh

Reputation: 41

How to read the value of variable in JS in the scope of JSP on the same page?

I have a JSP page in which third party sign-in plugin is used, which is JS. After sign-in is successful, the user-id obtained in JS has to be used in JSP to maintain session by storing that value.

For this, I tried 'manipulating' jQuery but that works only if the JS value is a literal or is pre-known. But here in this case, value is fetched at runtime as per sign in.

Also tried <% String s = "<script>document.writeln(var)</script>"; %> But again the above problem. works only when value is known before hand.

document.getElementById("ppurl").innerHTML = ppurl; prints the value. But I want to store it.

So, how to achieve the purpose of passing a variable's value in JS to JSP?

Upvotes: 0

Views: 1198

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Assuming your third party sign-in plugin is client-side JavaScript:

Remember that the JavaScript runs when the page reaches the client. The JSP code has long since completed and so is no longer in the picture.

You have three options that I can immediately see:

  1. Send the data to the server using Ajax or similar.
  2. Refresh the page (sending the login data to the server as part of the refresh).
  3. Update whatever it is on the page that you want to have this value in it via the DOM.

#1 and #2 should be fairly self-explanatory.

For #3: Say you have various forms on the page and you want to make sure that the login token or whatever it is you get from the client-side plugin gets sent with the form using a hidden field in the form with the name tokenField. You could do this:

function putTokenOnForms(token) {
    var forms, index, form;
    forms = document.getElementsByTagName("form");
    for (index = 0; index < forms.length; ++index) {
        form = forms[index];
        if (form.tokenField) {
            form.tokenField.value = token;
        }
    }
}

You can do much the same with links in a elements (adding to the href property of each link that goes back to your server), etc.

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

Store it in a cookie using JS. Read it back in JSP.

In your JS, after you get the userID, you can do:

document.cookie = 'myuserid='+userID;

In your JSP, you can read it back like:

Cookie[] cookies = request.getCookies();
String userID;
for(int i = 0; i < cookies.length; i++) { 
    Cookie c = cookies[i];
    if (c.getName().equals("myuserid")) {
        userID = c.getValue(); // c.getValue() will return the userID
        break;
    }
}

Upvotes: 0

Quentin
Quentin

Reputation: 943579

The page outputting the JavaScript to the client cannot read data back from that JavaScript.

You need to initiate a new HTTP request (e.g. using XMLHttpRequest or setting location.href) that passes the data back to the server and then read it in (e.g. from the query string or POST data).

Upvotes: 0

Related Questions