Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if session exists or not?

Tags:

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?

like image 874
sarah Avatar asked May 12 '10 11:05

sarah


People also ask

How do I check if a session exists?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable. For example: <?

How do you check if there is a session in Java?

Use request. getSession(false) to check if a user has a session.

How do you check if there is a session in PHP?

<? php if(! isset($_SESSION)) { session_start(); } ?>

What is session status?

Sessions or session handling is a way to make the data available across various pages of a web application. The session_status() function returns the status of the current session.


2 Answers

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).

like image 155
BalusC Avatar answered Sep 20 '22 01:09

BalusC


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.

like image 30
aioobe Avatar answered Sep 21 '22 01:09

aioobe