JSP - 如何在session.setAttribute中传递javascript var? [英] JSP - how to pass a javascript var in session.setAttribute?
问题描述
学习JSP的新手,并尝试在两个页面之间传递数据。
New to learning JSP, and trying out passing data between two pages.
我想知道是否可以将javascript变量传递给 session.setAttribute()
I'm wondering if it is possible to pass a javascript variable to session.setAttribute()
目前,我可以通过2个jsp文件传递一串文本,如下所示:
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")%>"
工作正常。
但是,是否可以将 var
传递到 session.setAttribute
?我将一些数据存储在javascript变量中,并希望将其发送到第二个JSP文件。
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.
例如:
var number = 7;
<%session.setAttribute("test", number);%>
我已经尝试了这个,我收到错误数字无法解析为变量
I've tried this out and I get the error "number cannot be resolved to a variable"
谢谢!
推荐答案
你不能这样做,因为javascript在客户端上执行&安培; JSP在服务器端执行。
You cannot do that since javascript executes on client & JSP executes on server side.
如果你想将javascript变量设置为JSP会话,那么你可以通过这个URL传递这个变量
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;
现在在JSP页面中收到此var
Now receive this var in your JSP page like this
String var = request.getParameter("param");
现在将其设置为会话
session.setAttribute("test", var);
编辑:
var number = 7;
<%session.setAttribute("test", number);%>
在上面的代码中,服务器只会执行< %%>内的代码。它不知道JSP标记之外的任何内容。所以,它也不会知道你的javascript变量数字
。
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
.
服务器执行代码&结果将被发送到浏览器,然后您的浏览器将执行该javascript代码 var number = 7;
。
Server executes the code & the result will be sent to the browser, then your browser will execute that javascript code var number=7;
.
希望,现在很清楚。
这篇关于JSP - 如何在session.setAttribute中传递javascript var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!