一、步骤
实现一个监听器的接口:(有N种)
1.1、编写一个监听器
package com.massimo.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数:统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听:看用户的一举一动
//一旦创建Session就会触发一次这个事件
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext ctx = httpSessionEvent.getSession().getServletContext();
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 httpSessionEvent) {
ServletContext ctx = httpSessionEvent.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);
}
}
1.2、在web.xml注册监听器
<!--注册监听器-->
<listener>
<listener-class>com.massimo.listener.OnlineCountListener</listener-class>
</listener>
<!--设置Session自动销毁-->
<session-config>
<!-- 1分钟后,自动销毁Session-->
<session-timeout>1</session-timeout>
</session-config>
1.3、测试
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>当前有<span><%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%></span>人在线</h1>
</body>
</html>
效果:
二、监听器在GUI中的理解
代码:
package com.massimo.test;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame("你好,马西莫");//新建一个窗体
Panel panel = new Panel(null);//面板
frame.setLayout(null);//设置窗体的布局
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(255, 249, 192));//设置背景颜色
panel.setBounds(50,50,300,300);
panel.setBackground(new Color(48, 209, 30));
frame.add(panel);
frame.setVisible(true);
//监听事件,监听关闭事件
frame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
System.out.println("打开");
}
public void windowClosing(WindowEvent e) {
System.out.println("关闭ing");
System.exit(0);
}
public void windowClosed(WindowEvent e) {
System.out.println("关闭ed");
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
System.out.println("激活");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("未激活");
}
});
}
}
测试:
点击相应的按钮,会在控制台打印出相应的语句!