JavaWeb-11-监听器
监听器的接口有很多,比如,HttpSessionListener…
以统计在线人数为例(监听session的接口)
-
实现监听接口
-
重写接口中的方法
//统计在线人数 public class OnlineCount implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); System.out.println(se.getSession().getId()); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount=new Integer(1); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } ctx.setAttribute("OnlineCount",onlineCount); } public void sessionDestroyed(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount=new Integer(0); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } ctx.setAttribute("OnlineCount",onlineCount); } }
-
在web.xml注册监听器
<!-- 注册监听器--> <listener> <listener-class>com.cmy.listener.OnlineCount</listener-class> </listener>
监听器的应用
GUI
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("hello frame");//构建一个窗体
Panel panel = new Panel(null);//面板
frame.setLayout(null);//设置窗体布局
frame.setBounds(500,400,500,500);
frame.setBackground(Color.blue);
panel.setBounds(100,100,300,300);
panel.setBackground(Color.ORANGE);
frame.add(panel);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("closing");
System.exit(0);
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("active");
}
});
System.out.println("hello");
}
}