Access Session variable from iframe

房东的猫 提交于 2020-01-25 04:22:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!