HttpSessionListener是监听session的接口,实现它的类要完成两个方法,因为这个实现类,直接卸载WEB.xml中,是服务器启动,就同时创建存在的,所以无法再交给Spring注入
package com.nms.www.util; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.nms.www.service.LoginService; public class SessionListen implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent arg0) { System.out.println("session开启"); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { System.out.println("session销毁"); if(arg0.getSession().getAttribute("user")!=null){ ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getSession().getServletContext());//获取上下文 LoginService loginService = (LoginService) ctx.getBean("loginService");//获取bean,这个bean在Spring的xml配置中,有注入 loginService.updateUserLogoutTime((Integer) arg0.getSession().getAttribute("logId")); } System.out.println("over"); } }
ApplicationContext