问题
I have a jsp where I set a session variable.
<% session.setAttribute("user", CrossSession.getUser(token)); %>
But when I try to read the session variable "user" within another jsp - which got loaded in an iframe (same host, server, etc.) - then I just get NullPointerException
<%= session.getAttribute("user").toString() %>
How can I get my session variables in iframes?
回答1:
Some browsers are quite restrictive as to sharing cookies with the iframe, particularly Safari. One way of bypassing this is to explicitly pass the session ID as path parameter of iframe's URL, hereby making use of "URL rewriting" support of the average servlet container as to session management (Tomcat supports it by default out the box).
<iframe src="some.jsp;jsessionid=${pageContext.session.id}" ...>
Note that I still assume that you're honest in saying that the iframe is served form the same host/domain.
回答2:
When you imbed a html framgment in an <iframe>
element, you are strictelly instructing the server to fire a new HTTP request, thus you will have an independent response within another context that won't include your session
object.
That's why you are receiving a NPE, because session
is null
.
But since all your jsp pages are within the same server, you can have the session
object passed across another embeded jsp but when using the <jsp:include />
directive.
So rather than embeding the jsp inside an iframe, embed the jsp like follows:
<jsp:include page="page_name.jsp" />
来源:https://stackoverflow.com/questions/25380619/access-session-variable-from-iframe