How to check if session exists or not?

两盒软妹~` 提交于 2019-12-29 03:27:27

问题


I am creating the session using

HttpSession session = request.getSession();

Before creating session I want to check if it exists or not. How would I do this?


回答1:


If you want to check this before creating, then do so:

HttpSession session = request.getSession(false);
if (session == null) {
    // Not created yet. Now do so yourself.
    session = request.getSession();
} else {
    // Already created.
}

If you don't care about checking this after creating, then you can also do so:

HttpSession session = request.getSession();
if (session.isNew()) {
    // Freshly created.
} else {
    // Already created.
}

That saves a line and a boolean. The request.getSession() does the same as request.getSession(true).




回答2:


There is a function request.getSession(boolean create)

Parameters:
    create - true to create a new session for this request if necessary; false to return null if there's no current session

Thus, you can simply pass false to tell the getSession to return null if the session does not exist.




回答3:


if(null == session.getAttribute("name")){  
  // User is not logged in.  
}else{  
  // User IS logged in.  
}  



回答4:


HttpSession session = request.getSession(true); if (session.isNew()) { ...do something } else { ...do something else }

the .getSession(true) tells java to create a new session if none exists.

you might of course also do:

if(request.getSession(false) != null){
    HttpSession session = request.getSession();
}

have a look at: http://java.sun.com/javaee/6/docs/api/javax/servlet/http/HttpServletRequest.html

cheers, Jørgen




回答5:


I would like to add that if you create a new session for every new user connecting to your website then your performance will take a hard hit. Use request.getSession(false) to check if a user has a session. With this method you don't create a new session if you're going to render a view based on if a user is authenticated or not.



来源:https://stackoverflow.com/questions/2818251/how-to-check-if-session-exists-or-not

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