Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  27] [ 3]  / answers: 1 / hits: 38122  / 9 Years ago, thu, october 1, 2015, 12:00:00

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!


More From » java

 Answers
30

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.


[#64876] Tuesday, September 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
janettejordynm questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Sat, May 23, 20, 00:00, 4 Years ago
Mon, Apr 6, 20, 00:00, 4 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
;