What if I want to know whether the session already existed or was just created?

Good question. The no-arg request method, getSession(), returns a session regardless of whether there’s a pre-existing session. Since you always get an HttpSession instance back from that method, the only way to know if the session is new is to ask the session.

image with no caption

Q:

Q: You get a session by calling request.getSession(), but is that the only way to get the session? Can’t you get it from the ServletContext?

A:

A: You get a session from the request object because—think about it—the session is identified by the request. When you call getSession() on the Container you’re saying, “I want a session for THIS client... either the session that matches the session ID this client sent, or a new one. But in either case, the session is for the client associated with this request.”

But there is another way that you can get a session... from a session event object. Remember, a listener class isn’t a servlet or JSP—it’s just a class that wants to know about the events. For example, the listener might be an attribute trying to find out when it (the attribute object) was added to or removed from a session.

The event-handling methods defined by the listener interfaces related to sessions take an argument of type HttpSessionEvent, or its subclass, HttpSessionBindingEvent. And HttpSessionEvent has a getSession() method!

So, if you implement ...

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.