3

New to learning JSP, and trying out passing data between two pages.

I'm wondering if it is possible to pass a javascript variable to session.setAttribute()

At the moment, I can pass a string of text through 2 jsp files like so:

JSP1:

<% String text = "hello";
session.setAttribute("test", text);%>

JSP2:

var someText = "<%=session.getAttribute("test")%>"

which works fine.

However, is it possible to pass through a var into session.setAttribute instead? I store some data in a javascript variable and would like to send it across to the second JSP file.

So for example:

var number = 7;
<%session.setAttribute("test", number);%>

I've tried this out and I get the error "number cannot be resolved to a variable"

Thanks!

1
  • have you tried like this <%session.setAttribute("test", <%=number%>);%> ? Commented Oct 1, 2015 at 10:21

1 Answer 1

12

You cannot do that since javascript executes on client & JSP executes on server side.

If you want to set javascript variable to JSP session, then you pass this variable through the URL like this

var number = 7;
window.location="http://example.com/index.jsp?param="+number;

Now receive this var in your JSP page like this

String var = request.getParameter("param");

Now set it in session

session.setAttribute("test", var);

EDIT :

var number = 7;
<%session.setAttribute("test", number);%>

In the above code, server will only execute the code inside <% %>. It does not know anything outside of the JSP tags. So, it will also dont know about your javascript variable number.

Server executes the code & the result will be sent to the browser, then your browser will execute that javascript code var number=7;.

Hope, now it is clear for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Brilliant, must remember to drill down in my head between client and server side! Will accept your answer when SO lets me in 4 mins :)
@Tom, Edited the answer for your better understanding. Hope it will help you.
@Harshit Hi with the code above, I am getting number cannot be resolved to a variable error message

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.