In this post, we will see how to check if HTTP session exists or not in java. Sometimes you need to check if session already exists or not and based on that perform some operations.
If you use below code to get the session:
1
2
3
HttpSession session=request.getSession();
You will never get above session object as null because request.getSession() will always give you session object, so you can use request.getSession(false) code to get session and if session does not exist, it will return null.
1
2
3
4
5
6
7
8
9
HttpSession session=request.getSession(false);
if(session==null){
// No session present, you can create yourself
session=request.getSession();
}else{
// Already created.
}
If you still want to use request.getSession(), you can use session.isNew() method to check if it is newly created or not.
1
2
3
4
5
6
7
8
HttpSession session=request.getSession();
if(session.isNew()){
// Just created.
}else{
// Already created.
}
I hope, it will help you to check if HTTP session exists or not.
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
In this post, we will see how to get HTTP response header in java. We have already seen how to send get or post request in java. I am using same example to demonstrate to get HTTP response header. [crayon-62fbe9afba0ff275659259/] [crayon-62fbe9afba108074102817/] When you run above code, you will get below output: [crayon-62fbe9afba10a713591779/] Was this post […]
In this post , we will see how to get HTTP request header in java. Sometimes, you want to print request header values. It is very simple to do it. You first need to get request object, then call getHeaderFields() on it to get all request header values. [crayon-62fbe9afba2ea156726800/] Spring MVC: If you are using […]
Table of ContentsHttpURLConnection example:Was this post helpful? In this post, we will see how to send HTTP Get/Post in java. There are many times when you need to send http get or post request. You can use HttpURLConnection for sending get/post request in java. It belongs to java.net package. HttpURLConnection example: We are going to […]