Monday 8 September 2014

HttpSessionListener using WebListener

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class SessionListenerEx implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("Session Created");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("Session Destroyed");
     }
}

import java.io.IOException;
import java.io.PrintWriter;
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{
        System.out.println("About to create session");
        HttpSession mySession = req.getSession();
        try(PrintWriter out = res.getWriter()){
            out.println(mySession.getId());
        }
        
        System.out.println("About to invalidate session");
        mySession.invalidate();
    }
}

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

Info:   About to create session
Info:   Session Created
Info:   About to invalidate session
Info:   Session Destroyed


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment