1 .先看看源代码类型的源代码
publicinterfaceservletcontextlistenerextendseventlistener {/* * * receivesnotificationthatthewebapplicationinitialiation * * pallservletcontextlistenersarenotifiedofcontext * initializationbeforeanyfiltersorservletsintheweb * applicationareinitialionatial @ paramscetheservletcontexteventcontainingtheservletcontext * thatisbeinginitialized */publi ized/* * receivesnotifificationtiontion shut down.* * pallservletsandfilterswillhavebeendestroyedbeforrer servletcontextlistenersarenotifiedofcontext * destruction . @ paramscetheservletcontexteventcontainingtheservletcontext * thatisbeingdestroyed */publicvoidcontextdestroyed (服务器连接}
此接口提供了两种创建和销毁ServletContext (即接收ServletContext )的方法。 这可以说是接收web APP应用程序的生命周期。 web APP应用程序启动时,将触发ServletContextEvent事件。 当此事件运行时,它被ServletContextListener侦听器监听,调用上下文初始化(servletcontexteventsce )方法,并从sce中提取servlet contentsce 例如,可以在创建的setAttribute (,obj )方法中设置数据,从servlet获取servlet context的实例,然后获取在getAttribute ) ''中设置的数据
实现代码:
publicclassmycontextlistenerimplementsservletcontextlistener { privateservletcontextcontext=空; publicvoidcontextinitialized (servletcontexteventevent ) context=event.getservletcontext ); useruser=database manager.getuser byid (1; context.setattribute('user1',user ); } publicvoidcontextdestroyed (servletcontexteventevent ) (useruser=) user ) context.getattribute ) ' user1'; 数据库管理器. update user data (user; this.context=null; }
如果web项目的最后一步是启用servlet上下文,则必须在web.xml中设置监听程序,并将web.xml放在正确的WEB-INF/classes目录中。
监听器监听器- classmyservletcontextlistener /监听器- class /监听器