Tuesday 9 September 2014

HttpSessionIdListener using addListener

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;

public class SessionIdLisn implements HttpSessionIdListener {
    @Override
    public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {
        System.out.println("Old Session id is " + oldSessionId);
    }
}

import javax.servlet.*;
import javax.servlet.annotation.WebListener;

@WebListener
public class ContextListener1 implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
         System.out.println("Context Listener1 created");
        ServletContext context = sce.getServletContext();
        context.addListener(SessionIdLisn.class);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Context Listener1 Destroyed");
    }
}

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(urlPatterns = {"/SampleApp"})
public class SampleApp extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException{
        HttpSession mySession = req.getSession();
        
        System.out.println("Changing Session id");
        req.changeSessionId();
        
        System.out.println("Changing Session id");
        req.changeSessionId();
        
        System.out.println("Changing Session id");
        req.changeSessionId();
    }
}

Run ' SampleApp' and you can observe the below messages in server console.

Info:   Context Listener1 created
Info:   Loading application [servlet] at [/servlet]
Info:   servlet was successfully deployed in 335 milliseconds.
Info:   Changing Session id
Info:   Old Session id is a0aa38b1c28d87a27e4334c5c2ed
Info:   Changing Session id
Info:   Old Session id is a0d84df3d5c8200218e5473512b8
Info:   Changing Session id
Info:   Old Session id is a0d84e0811b8b0f2e1b6b744f093



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment