如何验证/无效会话jsp/servlet? [英] How to validate/invalidate sessions jsp/servlets?
问题描述
当用户成功登录后,我在servlet中打开了会话:
I opened the session in my servlet when the user performed a successful login:
HttpSession session = request.getSession(true);
session.setAttribute("name", name);
然后我在logout.jsp中写了一个终止会话的消息:
then I wrote in the logout.jsp to terminate the session:
<%session.invalidate();%>
要检查会话是否有效,我正在这样做:
To check if a session is valid I am doing this:
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
但是它不起作用,即使在session.invalidate之后,我也正在使该会话有效. 有人知道我在哪里做错了吗?
But it is not working, I am getting the session valid even after the session.invalidate. Does anyone understand where am I doing wrong?
推荐答案
您应该调用session.getSession(false)-如果没有当前会话,则返回null.
you should call session.getSession(false) - which returns null if there is no current session.
根据 docs >
HttpSession#getSession(boolean create)
-create-如果需要,则为该请求创建一个新会话;为true;否则为false.如果没有当前会话,则返回false.
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.
所以会话值检查的正确方法是-
So the correct way of session value check would -
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", name);
,并且一旦您使会话无效-
and once you invalidate the session -
HttpSession session = request.getSession(false);
if(session!=null)
session.invalidate();
这篇关于如何验证/无效会话jsp/servlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!