监听器 listener
监听器的使用
- 继承listener接口
- 实现两个方法
demo1
public class Mylistener implements HttpSessionListener{
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
System.out.println(httpSessionEvent.getSession().getId());
Integer onlineCount =(Integer) servletContext.getAttribute("count");
if(onlineCount == null)
{
onlineCount = 1;
}else {
onlineCount++;
}
servletContext.setAttribute("count",onlineCount);
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
Integer onlineCount =(Integer) servletContext.getAttribute("count");
if(onlineCount == null)
{
onlineCount = 0;
}else {
onlineCount--;
}
servletContext.setAttribute("count",onlineCount);
}
}
注册监听器
<listener>
<listener-class>listener.Mylistener</listener-class>
</listener>
demo2 GUI-WindowListener
public class ListenerGui {
public static void main(String[] args) {
Frame frame = new Frame("测试监听器");
frame.setLayout(null);
Panel panel = new Panel(null);
frame.setBounds(100,100,500,500);
frame.setBackground(new Color(0,255,0));
panel.setBounds(50,50,200,150);
panel.setBackground(new Color(0,0,255));
frame.add(panel);
frame.setVisible(true);
/*
//窗口监听,适配器模式,可以不用实现所有方法
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("关闭");
System.exit(1);
}
});
*/
//窗口监听
frame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
System.out.println("opened");
}
public void windowClosing(WindowEvent e) {
System.out.println("closing");
System.exit(1);
}
public void windowClosed(WindowEvent e) {
System.out.println("closed");
}
public void windowIconified(WindowEvent e) {
System.out.println("Iconified");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("Deiconified");
}
public void windowActivated(WindowEvent e) {
System.out.println("Activated");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("Deactivated");
}
});
}
}