Showing posts with label http session. Show all posts
Showing posts with label http session. Show all posts

Thursday, March 24, 2011

Quick Recap: Chapters 20 to 24

Let us now quickly review what we learnt about Sessions in the previous chapters.

Session Introduction:

• We need Sessions to maintain or persist user information during a sequence of events on a website by a user
• Session persistence is usually implemented using Cookies but it can be implemented using URL Rewriting, or hidden form fields
• The getAttribute and setAttribute methods of the HttpSession are used to set and retrieve values from the Session
• You can get a session by using the getSession method of the Request class.
HttpSession session = request.getSession(true);

Session Event Listeners:

• The common event listeners we will encounter are: HttpSessionActivationListener, HttpSessionAttributeListener and HttpSessionBindingListener
• Each has methods that can help us capture and process actions like when a session is created/destroyed, when a value is added/removed from the session etc.

Session Invalidation:

• Invalidating a session after a certain time period is a common occurrence
• Usually websites that display sensitive information have a time-out of around 10 mins
• The session would automatically expire after the time-out is reached (If the session is inactive)

Key Terms we learnt in these chapters:

• Session
• Session ID
• Session Timeout
• Session Attribute
• Session Events
• Listeners

Previous Chapter: Chapter 24 - Session Tracking through URL Rewriting

Next Chapter: Self Test - Chapters 20 to 24

Chapter 23: Invalidating Sessions

Invalidating sessions is very important because, the session is going to contain some data, data that you might not want someone else to use. For example, lets say you login to your banks website on your office computer and receive an urgent call from your wife. In a hurry you leave your desk unattended and also without logging off the banks website. Now, lets say after an hour someone else from your office walks by your desk and sees that you are logged on to your banks website and are nowhere to be seen. They can use the website to transfer funds to their account. Wouldn't that be an issue? Yes, it would be. That is exactly why all secure websites have a session timeout feature wherein, the users session will be terminated automatically if it senses that the session has been idle for a few mins (Usually 5 mins or 10). This way, you are safe.
So, after all this story, I guess you know where I am coming to. We are going to learn how to invalidate a session in this chapter.

So, lets get started!!!

Invalidating Sessions

Invalidating sessions is important as well as tricky. You need to be cautious when you encounter questions in the exam that asks whether the session would be invalidated under a particular scenario. They might lure you into thinking that the session might be invalidated where in reality the session would be very much active.

Exam Trivia
When is session invalid Surfing to another Web site does not invalidate a session, but quitting the browser does. The user can surf from your page to somewhere else and back again without losing the session. The session will remain intact unless the user was away longer than the timeout.

The six most commonly used methods to invalidate a session are

• Calling HttpSession.setMaxInactiveInterval(int secs) method, explicitly setting how many minutes the session will last.
• The session will automatically be invalid after a certain time of inactivity (Tomcat default is 30 minutes). You need to remember that this 30 minutes is not a hard and fast rule for all servers. It might vary from one server to another and is configurable. So you can have it configured to last 25 mins in your server and I can have it to last 20 mins.
• The user closes all browser windows. Note that, here the session will timeout rather than directly triggering a session invalidation.
• The session will expire when it is explicitly invalidated by a servlet by calling invalidate().
• The server is stopped or crashes. Note that this event might not trigger a session invalidation. A Web container that permits failover might persist the session and allow a backup Web container to take over when the original server fails.
• You can set the default timeout in the web.xml file ().

Don't worry about the web.xml file just yet. We shall be covering it in great detail in future so for now just remember that you can set the session timeout interval in the web.xml file and that is as much you need to know at this point of time.

Previous Chapter: Chapter 22 - Session Event Listeners

Next Chapter: Chapter 24 - Session Tracking Through URL Rewriting

Chapter 22: Session Event Listeners

In one of the previous chapters, Interfaces & Listeners in the web context we saw about interfaces and event listeners. In this chapter we are going to take a look at the Event Listener that is linked to the HttpSession.

So, lets get started!!!

Session Event Listeners

The listeners that can be used to capture session event actions are:
1. HttpSessionActivationListener
2. HttpSessionAttributeListener
3. HttpSessionBindingListener

Lets look at them one by one in detail.

HttpSessionActivationListener

The purpose of this listener is to look for events such as when a session will be activated or passivated. The listener in turn extends the java.util.EventListener. The methods in it are:

• sessionDidActivate(HttpSessionEvent se) - This is the notification that the session has just been activated.
• sessionWillPassivate(HttpSessionEvent se)- This is the notification that the session is about to be passivated.

Exam Trivia:
Session Moving Between JVMs The specification dictates that a container that migrates a session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener.

HttpSessionAttributeListener:

The HttpSessionAttributeListener interface enables an object to monitor changes to the attribute lists of sessions within a given Web application. The HttpSessionAttributeListener in turn extends java.util.EventListener. The methods in it are

• attributeAdded(HttpSessionBindingEvent se)- This is the notification that an attribute has been added to a session.
• attributeRemoved(HttpSessionBindingEvent se)- This is the notification that an attribute has been removed from a session.
• attributeReplaced(HttpSessionBindingEvent se)- This is the notification that an attribute has been replaced in a session.

We can use these methods when monitoring the attributes of a particular session.

HttpSessionBindingListener

The last listener we are going to look at is the HttpSessionBindingListener. The HttpSessionBindingListener is used to track the events surrounding the binding and unbinding of a session. This event listener causes an object to be notified when it is bound to or unbound from a session. The interface is HttpSessionBindingListener in turn extends java.util.EventListener.

This will be triggered when a servlet is coded to explicitly unbind an attribute from a session, due to a session being invalidated or a session timeout. The methods in it are

• valueBound(HttpSessionBindingEvent event)- This is the notification to the object that it is being bound to a session and identifies the session.
• valueUnbound(HttpSessionBindingEvent event)- This is the notification to the object that it is being unbound from a session and identifies the session.

You might want to know when an object is added or removed from a session to handle, say, a shopping cart checkout. And this listener is just designed to help you with that.

Code Examples to Understand the Listener Usage:

Now that we know what these listeners are, lets look at a sample code that is going to handle these events. As you already know, if a class has to handle certain events, someone has to generate them, right? So here, the first code example is going to generate our events and the second guy is going to handle them.

Code 1:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestSessionEventsServlet extends HttpServlet {

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{

// Activities that trigger listener events
HttpSession session = request.getSession(true);
session.setAttribute("attributeName", "firstValue");
session.setAttribute("attributeName", "firstValue");
session.removeAttribute("attributeName");
session.invalidate();
}
}

The above code does nothing but, create a session and then set/remove attributes and then invalidate the session.

Code 2:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionActivityListener
implements HttpSessionListener,
HttpSessionAttributeListener
{
public void attributeAdded(HttpSessionBindingEvent event)
{
//do something when attribute is added
}

public void attributeRemoved(HttpSessionBindingEvent
event) {
{
//do something when attribute is removed
}

public void attributeReplaced(HttpSessionBindingEvent
event) {
{
//do something when an attribute is replaced
}

public void sessionCreated(HttpSessionEvent event) {
{
//do something when session is created
}

public void sessionDestroyed(HttpSessionEvent event) {
{
//do something when session is destroyed
}
}

The first servlet created the events we wished to capture and this above class will handle them. Actually I havent put any event handling code in any of the methods. They are all blank. But, in realtime, you would want to have code inside each of the event handling methods that would let you do something. For ex: when an attribute from session is removed which you feel is very important, you might log an error message for debugging purposes.

The even listeners are pretty useful when used appropriately. Well, that's about this chapter. Lets move on to the next one!!!

Previous Chapter: Chapter 21 - Storing & Retrieving Session Objects

Next Chapter: Chapter 23 - Invalidating Sessions

Tuesday, March 15, 2011

Chapter 15: The Session

In the previous chapter we took a look at how the HTTP Request can help us move data from the JSP to the Servlet and vice versa and the methods that are available in the Request object that would help us handle the data it carries.

In this chapter, we are going to look at the Session which is a super-set of the request and can contain data that needs to be retained across different pages.

So, lets get started!!!

The HTTP Session:

The Session is the place where data can be stored and retrieved across multiple hits from the same browser for a certain period of time. For example, lets say you want to login to your online banking website and the browser asks you to enter your login id and password after every click? It would be irritating isn’t it?

Exactly yes.

Thankfully we have the Http session.

When we logon to our bank website and enter our login id and password, the application saves our credentials in the session and uses it when we navigate between screens on the banks website.
Note: For reasons of safety and security, usually sessions in sensitive websites like a bank website or a stock brokers site, the session expires automatically after 5 minutes of inactivity or if the user presses the back or refresh buttons.

Getting the Session Object:

The session object can be obtained from the Request using the below line of code:

HttpSession session = request.getSession();


Setting & Getting Attributes from the Session:

We can set and retrieve attributes from the session using the setAttribute & getAttribute methods.

Ex:

session.setAttribute(“Key”, value); //Setting the value

Object obj = session.getAttribute(“Key”); //Getting the value

Here, “Key” is the identifier that will be used to locate the value saved in the session. The “Key” can be used to retrieve the value using the getAttribute() method.

Other Session Methods:

Some other methods available in the Session are:
1. getId() – Every session has a unique id and this method is used to get that id
2. getCreationTime() – To find out when the session was created
3. getLastAccessedTime() – To find out when the session was accessed last
4. getAttributeNames() – To retrieve all the values stored in the session as an Enumeration


To wrap up, sessions are what you can use to track a single user over a short time period (say 5 or 10 mins usually). You get the session object (HttpSession) from the request object. To track multiple users in your application, you can use the Context. Don't worry, that's our next stop…

For now, this chapter is over!!!

Previous Chapter: Chapter 14 - The Request Object

Next Chapter: Chapter 16 - Servlet Context
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers