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 any of the four listener interfaces related to sessions (we’ll get to that later in the chapter), you can access the session through the event-handling callback methods. For example, this code is from a class that implements the HttpSessionListener interface:

public void sessionCreated(HttpSessionEvent event) {
   HttpSession session = event.getSession();
   // event handling code
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset