Listener可以监听服务器端的相关状态变化,当服务器状态发生改变,将调用相应的Listener
这种机制可以成为回调机制,ServletContextListener配置如下
web.xml
<listener>
<listener-class>com.hugui.drp.util.listener.InitListener</listener-class>
</listener>
InitListener.java(在tomcat启动时就会被初始化)
package com.hugui.drp.util.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.hugui.drp.util.BeanFactory;
import com.hugui.drp.util.Constants;
/**
* 采用ServletContextListener完成初始化
* @author Administrator
*
*/
public class InitListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent arg0) {
}
public void contextInitialized(ServletContextEvent sce) {
System.out.println("创建系统的BeanFactory...");
//将抽象工厂放到ServletContext中
BeanFactory beanFactory = BeanFactory.getInstance();
sce.getServletContext().setAttribute("beanFactory", beanFactory);
//加入常量
sce.getServletContext().setAttribute("add", Constants.ADD);
sce.getServletContext().setAttribute("del", Constants.DEL);
sce.getServletContext().setAttribute("modify", Constants.MODIFY);
sce.getServletContext().setAttribute("showAdd", Constants.SHOW_ADD);
sce.getServletContext().setAttribute("query", Constants.QUERY);
sce.getServletContext().setAttribute("audit", Constants.AUDIT);
}
}
===================================================================================
===================================================================================
另外还有HttpSessionListener
Method Summary
void |
sessionCreated(HttpSessionEvent se) //当session被创建时调用,如jsp页面(session=true)打开时Notification that a session was created. |
void |
sessionDestroyed(HttpSessionEvent se) Notification that a session is about to be invalidated. |
HttpSessionAttributeListener(session的东西发生改变时:如往session里面添加东西)
Method Summary
void |
attributeAdded(HttpSessionBindingEvent se) //session.serAttribute("user");Notification that an attribute has been added to a session. |
void |
attributeRemoved(HttpSessionBindingEvent se) //如session.removeAttribute("user");Notification that an attribute has been removed from a session. |
void |
attributeReplaced(HttpSessionBindingEvent se) Notification that an attribute has been replaced in a session. |
HttpSessionBindingEvent
Method Summary
String |
getName() //能得到session的名字Returns the name with which the attribute is bound to or unbound from the session. |
HttpSession |
getSession() Return the session that changed. |
Object |
getValue() //得到session的值Returns the value of the attribute that has been added, removed or replaced. |