监听器存在以下对象
监听者:XxxxxListener - 所的监听者是的接口。
被监听者 :任意对象都可以成为被监听者 - 早已经存在。
监听到的事件:XxxxEvent- 永远是一个具体类,用来放监听到的数据
模拟一个观察者模式:
监听者:XxxxxListener - 所的监听者是的接口。
被监听者 :任意对象都可以成为被监听者 - 早已经存在。
监听到的事件:XxxxEvent- 永远是一个具体类,用来放监听到的数据
里面都有一个方法叫getSource() – 返回的是监听到对象。
观察者模式
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());
}
}
}
模拟一个观察者模式:
观察某人跑步这个事件:
public class Jiangyi {
/**
* @param args
*/
public static void main(String[] args) {
Zhu xiaozhu = new Zhu();
System.err.println(xiaozhu);
xiaozhu.addEatListener(new EatListener() {
public void eatting(ZhuEvent e) {
System.err.println("我看见小猪吃东西了");
System.err.println(e.getSource());
throw new RuntimeException("不让你吃了");
}
});
xiaozhu.eat();
}
}
interface EatListener {
public void eatting(ZhuEvent e);
}
class Zhu {
private EatListener eatListener;
public void eat() {
if (eatListener != null)
eatListener.eatting(new ZhuEvent(this));
System.err.println("小猪在吃东西");
}
public void addEatListener(EatListener eatListener) {
this.eatListener = eatListener;
}
}
class ZhuEvent {
private Object src;
public ZhuEvent(Object src) {
this.src = src;
}
public Object getSource() {
return src;
}
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
监听者 | 被监听者 | 监听到事件对象 |
HttpSession – 监听HttpSession活化和顿化。 | ||
HttpSession – 监听session的属性变化的。S.setAttributee(); | ||
HttpSession - 监听哪一个对象,绑定到了session上。S.setAtrri(name,User); |
| |
HttpSesion – 监听sessioin创建销毁 | ||
ServletContext – 属性变化的 |
| |
servletContext 创建销毁 |
| |
ServletRequestListener - serlvetRequestAttibuteListner | Rrequest -创建销毁 |
|