import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; 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 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(SessionListenerEx.class); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("Context Listener1 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: Context Listener1 created Info: Loading application [servlet] at [/servlet] Info: servlet was successfully deployed in 286 milliseconds. Info: About to create session Info: Session Created Info: About to invalidate session Info: Session Destroyed
No comments:
Post a Comment