• 监听器


    监听器

    监听器存在以下对象

    监听者:XxxxxListener - 所的监听者是的接口。

    被监听者 :任意对象都可以成为被监听者 - 早已经存在。

    监听到的事件:XxxxEvent- 永远是一个具体类,用来放监听到的数据里面都有一个方法叫getSource() – 返回的是监听到对象。

    观察者模式
    package cn.itcast.demo;
    public class MyFrame extends JFrame {
        public MyFrame() {
            JButton btn = new JButton("你好");
            System.err.println("btn: is:"+btn.hashCode());
            btn.addActionListener(new MyListener());
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //获取容器
            Container con= getContentPane();
            //设置布局
            con.setLayout(new FlowLayout());
            con.add(btn);
            
            setSize(300, 300);
            setVisible(true);
        }
        public static void main(String[] args) {
            new MyFrame();
        }
        //实现一个监听者
        class MyListener implements ActionListener{
            //监听方法
            public void actionPerformed(ActionEvent e) {
                System.err.println("我监听到了:"+e.getSource().hashCode());
            }
        }
    }
    package cn.itcast.demo;
    public class TestObersver {
        public static void main(String[] args) {
            Person person = new Person();//声明被观察者
            System.err.println("pp:"+person);
            person.addPersonListener(new PersonListener() {
                public void running(PersonEvent pe) {
                    System.err.println("你正在跑....."+pe.getSource());
                    throw new RuntimeException("他跑了。。。");
                }
            });
            person.run();
        }
    }
    class Person{
        private PersonListener pl;
        public void addPersonListener(PersonListener pl){
            this.pl = pl;
        }
        public void run(){
            if(pl!=null){
                pl.running(new PersonEvent(this));
            }
            System.err.println("我正在跑步......");
        }
    }
    interface PersonListener{
        void running(PersonEvent pe);
    }
    class PersonEvent{
        private Object src;
        public PersonEvent(Object obj) {
            this.src=obj;
        }
        public Object getSource(){
            return src;
        }
    }
    在JavaWeb中的监听器分类

    在Javaweb中存在三个被监听对象:

    HttpServletRequest

    HttpSessoin

    ServletContext

    监听者

    被监听者

    监听到事件对象

    HttpSessionActivationListener

    HttpSession – 监听HttpSession活化和顿化。

    HttpSessionEvent

    HttpSessionAttributeListener

    HttpSession – 监听session的属性变化的。S.setAttributee();

    HttpSessionBindingEvent

    HttpSessionBindingListener

    HttpSession - 监听哪一个对象,绑定到了session上。S.setAtrri(name,User);

     

    HttpSessionListener

    HttpSesion – 监听sessioin创建销毁

    HttpSessionEvent

    ServletContextAttributeListener

    ServletContext – 属性变化的

     

    ServletContextListener

    servletContext 创建销毁

     

    ServletRequestListener - serlvetRequestAttibuteListner

    Rrequest -创建销毁

     

    实现一个监听器HttpServletRequest的创建销毁

    第一步:实现一个类:

    package cn.itcast.listener;
    import javax.servlet.ServletRequestEvent;
    import javax.servlet.ServletRequestListener;
    public class RequestListener implements ServletRequestListener {
        public void requestDestroyed(ServletRequestEvent sre) {
            System.err.println("request销毁了:");
            Object o = sre.getSource();
            System.err.println("这个o is :"+o);//apache.RequestFaced@22222
        }
        public void requestInitialized(ServletRequestEvent sre) {
            System.err.println("request创建了:");
            Object o = sre.getSource();
            System.err.println("这个o是 :"+o);//apache.RequestFaced@22222
        }
    }

    第二步:必须要配置到web.xml

    <listener>
    <listener-class>cn.itcast.listener.RequestListener</listener-class>
    </listener>

    说明:

    1:配置一个Listener只要求提供类名就可以了。

    2:在tomcat启动时,会自动的初始化这个监听器类。

    3:tomcat创建的Listner,Serlvet,Filter都是单列的.

    监听seession中的属性变化的

    Session.setAttribute(“name”,”Jack”); == > 添加新的属性

    Seession.setAttribute(“name”,”Rose”) == > replace重新设置name值。

    Session.removeAttribute(“name”) = > 删除某个属性

    void

    attributeAdded(HttpSessionBindingEvent se) Session.setAttribute(“name”,”Jack”); == > 添加新的属性
              Notification that an attribute has been added to a session.

    void

    attributeRemoved(HttpSessionBindingEvent se) Session.removeAttribute(“name”) = > 删除某个属性
              Notification that an attribute has been removed from a session.

    void

    attributeReplaced(HttpSessionBindingEvent se)Seession.setAttribute(“name”,”Rose”) == > replace重新设置name值。

              Notification that an attribute has been replaced in a session.

    package cn.itcast.listener;
    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    public class AttributeListener implements HttpSessionAttributeListener {
        //sessoin.setAttribute("addr",中国北京);
        public void attributeAdded(HttpSessionBindingEvent e) {
            String name = e.getName();//--addr
            Object value = e.getValue();//获取sesion的value值
            System.err.println("添加了一个新的属性:"+name+","+value);
        }
        //session.removeAttribute("addr"); - tomcat容器
        public void attributeRemoved(HttpSessionBindingEvent e){
            String name = e.getName();
            Object value = e.getValue();
            System.err.println("删除了一个属性:"+name+","+value);
        }
        //sessoin.setAttribute("addr",中国北京);
        //sessoin.setAttribute("addr",上海);
        public void attributeReplaced(HttpSessionBindingEvent e) {
            String name = e.getName();
            Object oldValue = e.getValue();
            HttpSession session = e.getSession();
            Object newValue = session.getAttribute(name); 
            System.err.println("重新设置了一个值:"+name+","+oldValue+",newValue:"+newValue);
            
        }
    }

    ServletContextListener 用于监听SevletContext的创建

    在web中的所的监听器都是全局的 - 都是在项目启动时直接由tomcat创建。监听器没有顺序。只是监听的对象不一样。在一个项目中可以存在多个监听器。

    package cn.itcast.listener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.PrintWriter;
    import java.net.URL;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    public class MyContextListener implements ServletContextListener {
        //在启动时读取数据库之前保存的数据
        public void contextInitialized(ServletContextEvent sc) {
            System.err.println("application被创建了:"+sc.getServletContext());
            URL url = MyContextListener.class.getClassLoader().getResource("count.txt");
            String path = url.getFile();
            System.err.println(path);
            try {
                BufferedReader bf = new BufferedReader(new FileReader(path));
                String line = bf.readLine();
                Integer count = Integer.valueOf(line);
                sc.getServletContext().setAttribute("count",count);
                System.err.println("初始的值是:"+count);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            
            
        }
        //在销毁这个对象时保存一些数据到数据库或是文件中
        public void contextDestroyed(ServletContextEvent e) {
            System.err.println("销毁了:"+e.getServletContext());
            //保存到文件中去
            URL url = MyContextListener.class.getClassLoader().getResource("count.txt");
            String path = url.getFile();
            System.err.println(path);
            File file = new File(path);
            try {
                PrintWriter out = new PrintWriter(file);
                //获取applicat的数据
                Integer count = (Integer) e.getServletContext().getAttribute("count");
                out.print(count);
                out.close();
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
            
            
        }
    }

    在项目启动时一次加载所有的配置文件。

    HttpSessionBindingListener - 此类是用于监听一个 Bean是否被放到了Session中。

    Person p = new Person();.
    Session.setAttriute(“pp”, p);
    实现此类的Bean不需要配置到web.xml。

    HttpSessionActivationListener - 监听一个Sesison被保存到一个文件中的过程

    也需要一个Bean。实现HttpSessionActivationListener接口。此类也不需要配置到web.xml

    Person p  = new Person()  implemnts HttpSessionActivationListener{
    Actived….
    }
    Session.setAttribute(“p”,p);

    第一步:书写Bean实现HttpSessionActivationListener

    package cn.itcast.domain;
    import java.io.Serializable;
    import javax.servlet.http.HttpSessionActivationListener;
    import javax.servlet.http.HttpSessionEvent;
    public class Person implements Serializable,HttpSessionActivationListener{
        private String name;
        public Person() {
        }
        public Person(String name) {
            this.name = name;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void sessionWillPassivate(HttpSessionEvent se) {
            System.err.println("保存到文件中去了..."+this.getName());
        }
    
        public void sessionDidActivate(HttpSessionEvent se) {
            System.err.println("从文件中活化了...."+this.getName());
        }
        @Override
        public String toString() {
            return "Person [name=" + name + "]";
        }
    }

    第二步:配置这个项目

    <Context  docBase="D:\programfiles\MyEclipse10\wk3\day21\WebRoot">
        <Manager className="org.apache.catalina.session.PersistentManager"
                 saveOnRestart="true">
                <Store className="org.apache.catalina.session.FileStore"
                       directory="d:/a">
                </Store>
        </Manager>
    </Context>

    第三步:测试

    <%
            if(session.getAttribute("p")==null){
                int a = new Random().nextInt(100);
                Person p = new Person(""+a);
                session.setAttribute("p",p);
            }
            //保存cookie
            Cookie c = new Cookie("JSESSIONID",session.getId());
            c.setMaxAge(60*30);
            c.setPath(request.getContextPath());
            response.addCookie(c);
        
        %>
        <hr/>
        ${p}
        <hr/>
        <%=session.getId()%>
  • 相关阅读:
    LLVM 笔记(二)—— PHI node
    Ubuntu,sublime快速启动
    ubuntu14.04安装Thinkphp
    ubuntu,scrapy安装
    ubuntu,sublime text 3中文输入的问题
    ubuntu安装beatifulsoup,pip,creepy
    ubuntu,系统设置无法打开
    Ubuntu14.04安装完成的基本配置
    在Sublime Text 3中添加snippet
    领航工作室启用新域名啦!
  • 原文地址:https://www.cnblogs.com/sunhan/p/3542128.html
Copyright © 2020-2023  润新知