HttpSessionListener vs ServletContextListener




Asked on July 27, 2018
What is difference between HttpSessionListener vs ServletContextListener in Servlet with examples?


Replied on July 27, 2018
HttpSessionListener

HttpSessionListener is an interface that receives notification events about HttpSession lifecycle changes. HttpSessionListener provides sessionCreated() and sessionDestroyed() method. sessionCreated() executes just after a session is created. sessionDestroyed() executes just before session is invalidated. The sample use of HttpSessionListener is tracking sessions created and destroyed. To use HttpSessionListener we need to create its implementation listener class and that class will either be annotated with @WebListener or configured in web.xml using <listener> tag. @WebListener annotation is supported by Servlet 3.0 +.

public class SessionCountListener implements HttpSessionListener {
private final AtomicInteger sessionCount = new AtomicInteger();
@Override
public void sessionCreated(HttpSessionEvent se) {
sessionCount.incrementAndGet();
setActiveSessionCount(se);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
sessionCount.decrementAndGet();
setActiveSessionCount(se);
}
private void setActiveSessionCount(HttpSessionEvent se) {
se.getSession().getServletContext()
   .setAttribute("activeSessions", sessionCount.get());
System.out.println("Total Active Session: " + sessionCount.get());
}


ServletContextListener

It receives notification events about ServletContext lifecycle changes. To create ServletContextListener we have to override the methods contextInitialized(ServletContextEvent sce) and contextDestroyed(ServletContextEvent sce)

public class AdminInfoListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContextEvent initialized.");
ServletContext sc = sce.getServletContext();
sc.setAttribute("admin", "Krishna");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.removeAttribute("admin");
System.out.println("ServletContextEvent destroyed.");
}





Write Answer










©2024 concretepage.com | Privacy Policy | Contact Us