当用户成功登录时,我在我的 servlet 中打开了 session :
HttpSession session = request.getSession(true);
session.setAttribute("name", name);
然后我在 logout.jsp 中写了终止 session :
<%session.invalidate();%>
要检查 session 是否有效,我正在这样做:
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
但它不起作用,即使在 session.invalidate 之后我也使 session 有效。
有谁明白我哪里做错了?
最佳答案
您应该调用 session.getSession(false) - 如果没有当前 session ,则返回 null。
根据 docs
HttpSession#getSession(boolean create)
- create - true to create a new session for this request if necessary; false to return null if there's no current session.
所以 session 值检查的正确方法是 -
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", name);
一旦你使 session 无效 -
HttpSession session = request.getSession(false);
if(session!=null)
session.invalidate();
关于jsp - 如何验证/无效 session jsp/servlets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14445024/