1:首先需要导入的包
2:在web.xml中添加监听
3:
ServletContextListener监听ServletContext。当创建ServletContext时,激发 contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。
用这个监听器,tomcat启动和停止前你想干什么干什么
package com.eoopen.listener; import java.util.List; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.springframework.data.redis.core.RedisTemplate; import com.eoopen.util.Constant; import com.eoopen.util.ContextUtil; import com.eoopen.util.XMPPConnectionUtils; import com.eoopen.xmpp.loginin.ClientUser; import com.eoopen.xmpp.loginin.ClientUserService; import com.eoopen.xmpp.loginin.OfUser; public class InitServletContextListener implements ServletContextListener{ public void contextInitialized(ServletContextEvent sce) { System.out.println("-------------------------contextInitialized"); try { //创建openfire连接,账号登陆 XMPPConnection connection = XMPPConnectionUtils.getConnection(); connection.login(XMPPConnectionUtils.NAME, XMPPConnectionUtils.PASSWORD); //初始化openfire后台登陆的sessionId XMPPConnectionUtils.loginBackstage(); //初始化用户缓存队列 initUserCacheQueue(); } catch (XMPPException e) { System.out.println("------------------------------服务器初始化登陆openfire服务器失败"); e.printStackTrace(); } } public void contextDestroyed(ServletContextEvent sce) { System.out.println("--------------------------contextDestroyed"); XMPPConnectionUtils.closeConnection(); } }
时间: 2024-10-25 03:29:19