java web三大組件:servlet引润,listener吝镣,filter烂叔。
java web中的監(jiān)聽(tīng)器
事件源:三大域隘截!
- servletContext
- HttpSession
- ServletRequest
都有嗅虏,生命周期監(jiān)聽(tīng)和屬性監(jiān)聽(tīng)
生命周期監(jiān)聽(tīng):
1洛姑、創(chuàng)建是調(diào)用
2、銷(xiāo)毀時(shí)調(diào)用
屬性監(jiān)聽(tīng):
1皮服、添加屬性調(diào)用
2楞艾、替換屬性調(diào)用
3、移除屬性調(diào)用
舉個(gè)例子:
public class InitConfigListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
LogWriter.info("=======================初始化")
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
<listener>
<listener-class>com.fuiou.web.listener.InitConfigListener</listener-class>
</listener>
HttpSessionBindingListener
public class User implements HttpSessionBindingListener{
private String username;
private int age;
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("session 添加了 user");
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("session 移除了 user");
}
}
只要實(shí)現(xiàn)HttpSessionBindingListener接口龄广,那么當(dāng)往session中添加user屬性硫眯,就會(huì)觸發(fā)valueBound方法,移除就會(huì)觸發(fā)valueUnbound方法择同。