**
- ServletContextListener
**
用来在程序启动时 初始化 属性
@WebListener
public class ServiceListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserServiceImpl userServiceImpl = context.getBean("userServiceImpl", UserServiceImpl.class);
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("service",userServiceImpl);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext().removeAttribute("service");
}
}
- ServletContextAttributeListener
在程序运行过程中,req.getServletContext().setAttribute(“”,something); 时 发挥作用
public class ServiceListener2 implements ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("添加了一个ServletContext属性");
}
@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("移除了一个ServletContext属性");
}
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
System.out.println("修改了一个ServletContext属性的作用范围");
}
}
在第一段代码中使用注解配置监听器 --> @WebListener
在xml中配置 要放在servlet前面