0

I read another answer on stack overflow where use of session variables stored by spring mvc from jsp pages is explained.

What I wish to know is, can I access such session variables from JavaScript code in HTML front end for a web app that uses spring for it's backend? If yes then how do I access session variables from JavaScript ?

2 Answers 2

1

No, not directly.

Consider that session variables exist in memory on the server and JavaScript executes in the browser on the client. Once this is clear, it should also be clear why you can't directly access session variables in client-side JavaScript.

If you need to read session-variables in your JavaScript code, there are ways around though.

  1. You can render the value as a JavaScript variable on the page
  2. You create a simple AJAX service (REST/JSON) so your page can make a request to the server using AJAX in the JavaScript and get the session variable value back
Sign up to request clarification or add additional context in comments.

1 Comment

with ref to point 2 in your answer, cant such a service be easily abused by for eg hackers? Also can you point me to some sample code for both your points? Thanks
1

You will have to iterate over session variables and print out a script which will set session attributes as array.

for eg in your jsp code:

add following line

<script>
var session= new Array();
<%
for (Enumeration e = session.getAttributeNames() ; e.hasMoreElements() ;) {
     Object obj= e.nextElement();
     %>session['<%=obj%>']='<%=(String)session.getAttribute(obj)%>';<%
   }
%>
</script>

This is assuming your session attributes are String.

Now you can access session attributes in browser javascript

for eg: session['key1'] will give String representation of Session attribute corresponding to key1 in server.

1 Comment

You realize you call e.nextElement() twice in each loop in your example, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.