JavaWeb-11-監聽器
監聽器的接口有很多,比如,HttpSessionListener…
以統計線上人數為例(監聽session的接口)
- 實作監聽接口
JavaWeb-11-監聽器JavaWeb-11-監聽器 - 重寫接口中的方法
//統計線上人數 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");
}
}