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?
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: <?
Use request. getSession(false) to check if a user has a session.
<? php if(! isset($_SESSION)) { session_start(); } ?>
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.
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)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With