I'm trying to create a login filter in my java web project. The problem is, when i call request.getSession(false), the session object returned is not null, in other words, the session is active. But I'm sure I didn't call getSession() in any other place of my code. Even if I delete this filter, it doesnt work. If I open my browser dev tools, in network tab, it shows me a jsessionid set. It's session being set automatically?
-
2The session would normally be created automatically. Particularly if the client is accessing a dynamic resource like a servlet or a jsp. – ernest_k May 31 '19 at 05:27
-
@ernest_k So, how I am able to make a login filter if a session is always opened? – Raphael Andrade May 31 '19 at 13:13
-
A session does not imply login – ernest_k May 31 '19 at 13:19
-
But how I am able to make sure it's a login session? – Raphael Andrade May 31 '19 at 13:23
-
you get to decide and implement that, maybe storing data in the session... – ernest_k May 31 '19 at 13:26
-
Are you using JSP pages? – Heraldo May 31 '19 at 15:08
-
Yeah, i'm using JSP – Raphael Andrade Jun 01 '19 at 00:13
-
What's the point to have a HttpSession class/api if i have to implement everything by myself? – Raphael Andrade Jun 01 '19 at 00:26
1 Answers
If you want to track a "logged in user", then I think what you are looking for is to track it using the HttpSession, like this:
HttpSession session = request.getSession();
session.setAttribute("loggedInUser", userObject);
Ypu can retrieve it from the session whenever you need it with:
Object loggedInUser = session.getAttribute("loggedInUser");
And later, when the user needs to "log out", clear the stored user from the session:
session.removeAttribute("loggedInUser");
To answer your question in the comments What's the point to have a HttpSession class/api if i have to implement everything by myself?
: a HttpSession
represents a conversation with a specific client, so that subsequent requests from the same client can be identified and processed properly. It does not represent at all a "logged in user", that is a specific requirement from the domain - not all services require authentication.
Finally, if you need more details of when a JSESSIONID cookie is created, read this question.

- 407
- 2
- 11