How to check whether the session is existed?

There are two ways to detect whether the session is existed.

1) request.getSession(); + session.isNew()

– Retrieve a session from “request.getSession();”, this function will always return a session no matter what, it’s equivalent to request.getSession(true);. The only problem is you do not know whether this is new or existed session.
– Later you can check with “session.isNew()”, true if this is a new session else return an existed session.


public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException{

		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();

		HttpSession session = request.getSession();
		if(session.isNew()){
			pw.println("New session is jutst created");
		}else{
			pw.println("This is old session");
		}	
	}

2) request.getSession(false); + if(session ==null)

– Retrieve a session from “request.getSession(false);”, this function will return a session if existed , else a null value will return.
– Later you can do a “null” checking with the session object, null means no existed session available.


public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
	
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
		
		HttpSession session = request.getSession(false);
		if(session ==null){
			pw.println("No session available");
		}else{
			pw.println("This is old session");
		}	
	}

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Awadhesh??? Recent comment authors
newest oldest most voted
Awadhesh
Guest
Awadhesh

session.isNew() always returns false when used with jsp. since i am using session in my jsp so i cannot use <%@ page session="false" in my jsp file. Please suggest some solution.

???
Guest
???

Hello, mkyong. I am one of your fans. Would you please give a complete example of using session(create , check , destroy, put data in) in spring MVC framework ?