当一个浏览器第一次访问网站的时候,J2EE应用服务器会新建一个HttpSession对象 ,并触发 HttpSession创建事件 ,如果注册了HttpSessionListener事件监听器,则会调用HttpSessionListener事件监听器的sessionCreated方法。相反,当这个浏览器访问结束超时的时候,J2EE应用服务器会销毁相应的HttpSession对象,触发 HttpSession销毁事件,同时调用所注册HttpSessionListener事件监听器的sessionDestroyed方法。
1.创建SessionCounter 这个类,并注入一个bean:
@Service
public class SessionCounter implements HttpSessionListener {
/*@Autowired 无法注入通过WebApplicationContextUtils 得到Spring容器的实例。根据bean的名称返回bean的实例。
private UserService userService;*/
private static int activeSessions =0;
/* Session创建事件 */
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession( ).getServletContext( );
System.out.println("session创建");
}
/* Session失效事件 */
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx=se.getSession().getServletContext();
HttpSession sess = se.getSession();
Users u=new Users();
u.setId((Integer) sess.getAttribute("id"));
System.out.println((Integer) sess.getAttribute("id")+"aaaaaaaaa"+sess.getAttribute("username"));
u.setLoginState(2);
//通过抽象的私有方法得到Spring容器中Bean的实例。
UserService userService=(UserService)this.getObjectFromApplication(sess.getServletContext(),"userServiceImpl");
userService.updateUsers(u);
System.out.println(u.getLoginState().toString());
}
/**
* 通过WebApplicationContextUtils 得到Spring容器的实例。根据bean的名称返回bean的实例。
* @param servletContext :ServletContext上下文。
* @param beanName :要取得的Spring容器中Bean的名称。
* @return 返回Bean的实例。
*/
private Object getObjectFromApplication(ServletContext servletContext,String beanName){
//通过WebApplicationContextUtils 得到Spring容器的实例。
ApplicationContext application=WebApplicationContextUtils.getWebApplicationContext(servletContext);
//返回Bean的实例。
return application.getBean(beanName);
}
}
2.web.xml文件中做相关的配置。<listener>
<listener-class>com.wangyun.service.impl.SessionCounter</listener-class>
</listener>
session过期时间单位:分钟
<session-config>
<session-timeout>1</session-timeout>
</session-config>
HttpSessionListener主要注意的是bean的注入,只能从spring容器中得到bean实例。