0

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?

1 Answers1

0

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.

Heraldo
  • 397
  • 1
  • 11