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"); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <listener> <description>HttpSessionListener</description> <listener-class>SessionListenerEx</listener-class> </listener> </web-app>
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
No comments:
Post a Comment