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