Skip to Content
Head First Servlets and JSP, 2nd Edition
book

Head First Servlets and JSP, 2nd Edition

by Bryan Basham, Kathy Sierra, Bert Bates
March 2008
Intermediate to advanced
911 pages
20h 31m
English
O'Reilly Media, Inc.
Content preview from Head First Servlets and JSP, 2nd Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck

Publisher Resources

ISBN: 9780596516680Errata PageSupplemental Content