javaweb学习笔记之监听器

    技术2024-04-07  97

    监听对象

    三个监听对象:request session application


    监听对象的创建和销毁

    request: ServelrRequestListenersession: HttpSessionListenerapplicdtion: ServetContextListener

    每个监听器各自提供了2个方法:监听开始、监听结束的方法 ServetContext在servlet容器启动时自动创建


    监听对象中属性的变更 request: ServletRequestAttributeLi stner sess ion: HttpSessionAttri buteListener appl ication: ServletContextAttr i buteListener


    开发步骤

    编写监听器web.xml中注册监听器看情况是否使用

    例子: 实现监听器接口

    //统计网站在线人数 : 统计session public class OnlineCountListener implements HttpSessionListener { //创建session监听: 看你的一举一动 //一旦创建Session就会触发一次这个事件! 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); } //销毁session监听 //一旦销毁Session就会触发一次这个事件! 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); } /* Session销毁: 1. 手动销毁 getSession().invalidate(); 2. 自动销毁 */ }

    web.xml中注册监听器

    <!--注册监听器--> <listener> <listener-class>com.kuang.listener.OnlineCountListener</listener-class> </listener>

    GUI编程中使用监听器

    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(0,0,255)); //设置背景颜色 panel.setBounds(50,50,300,300); panel.setBackground(new Color(0,255,0)); //设置背景颜色 frame.add(panel); frame.setVisible(true); //监听事件,监听关闭事件 frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); } }); } }
    Processed: 0.015, SQL: 9