O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required