我想在 JSP 页面中重置 session 而不使其失效。
这样做的原因是,用户可能已经使用该 session 打开了一个页面并且使它无效会抛出一个 NullPointerException
。由于已经捕获了一个新的 session ,我不想添加额外的流行语。目标是清除所有属性。
我正在寻找类似的东西:
session = new HttpSession(); //this does obviously not work
另一种选择是(?)
while(session.getAttributeNames().hasMoreElements()){
session.removeAttribute(session.getAttributeNames().nextElement());
} //cleans session?
但我不确定这是否会删除一些必要的 session 属性,例如登录数据。
有什么好的方法吗?
编辑:最好的解决方案是,每次打开某个页面时,您都会为该窗口/选项卡创建一个新 session ,直到您关闭该选项卡或在此选项卡中重新访问该页面。这个问题是在试图解决 this problem. 时发生的
最佳答案
是的,有一个很好的方法可以做到这一点。创建一个包装 HttpSession
对象的类并实现一个 Map
接口(interface)。在实现中,您可以在不使 session 失效的情况下操作 session 属性。类似于 SessionMap
的实现代码在Struts2框架中。您可以阅读 SessionMap
的文档页面在这里。
A simple implementation of the
Map
interface to handle a collection of HTTP session attributes. TheentrySet()
method enumerates over all session attributes and creates aSet
of entries. Note, this will occur lazily - only when the entry set is asked for.
SessionMap 的类似实现你可以在 JSF 中找到。您可以找到文档页面 here .
public class SessionMap extends java.util.AbstractMap<java.lang.String,V>
See Also:
javax.faces.context.ExternalContext#getSessionMap()
如果您使用这些框架中的任何一个,您可以使用或覆盖 clear()
方法来获得您想要的内容。
关于java - 在jsp中重置 session 而不失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35156546/