Here’s a simple “HttpSessionListener” example to do the login and logout time entry in the database.using service
Java Source
package com.jayesh; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MySessionListener implements HttpSessionListener {
private MyDbService myDbService; public static int getTotalActiveSession(){ return totalActiveSessions; } @Override public void sessionCreated(HttpSessionEvent arg0) {
ApplicationContext ctx = WebApplicationContextUtils. getWebApplicationContext(session.getServletContext()); MyDbService myDbService= (MyDbService) ctx.getBean("myDbServiceBeaniId"); myDbService.addLoginTime(); System.out.println("session time is inserted in database");
} @Override public void sessionDestroyed(HttpSessionEvent arg0) { MyDbService myDbService= (MyDbService) ctx.getBean("myDbServiceBeaniId"); System.out.println("sessionDestroyed and logout time inserted"); } }
web.xml
<web-app ...> <listener> <listener-class>com.jayesh.SessionCounterListener</listener-class> </listener> </web-app>
spring-secutity.xml
<beans:bean id="myBdServiceBeanId" class="com.jayesh.service.MyDbServices"></beans:bean>
How it work?
- If a new session is created , e.g “request.getSession();” , the listener’s sessionCreated() will be executed.
- If a session is destroyed, e.g session’s timeout or “session.invalidate()”, the listener’s sessionDestroyed() will be executed.
- If a session is destroyed, e.g session’s timeout or “session.invalidate()”, the listener’s sessionDestroyed() will be executed.
HttpSession session = request.getSession(); //sessionCreated() is executed session.setAttribute("url", "mydomain.com"); session.invalidate(); //sessionDestroyed() is executed
No comments:
Post a Comment