Main Tutorials

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 Author

author image
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

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Hariom Kumar Garg
4 years ago

Hi All,
I am using a spring boot application with angular.
1) I am calling a servlet from angular and on servlet one attribute value setting in session. and return it in response.
2) Now calling a restapi . in this restapi method on controller i want to that session value so i am getting session null if i am using
public String add(@RequestBody Captcha captcha, HttpServletRequest request) {
request.getSession().getAttribute(“cap”); // cap value was set in session on servlet
}

is it possible?
please confirm. if yes how?

Awadhesh
5 years ago

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.

???
10 years ago

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 ?