文章目录
什么是监听器
监听器是一个实现特定接口的普通Java程序(也就是Java类),这个程序专门用于监听另一个Java对象的方法调用或属性改变 ,当被监听对象调用某个方法或者属性改变时,监听器的某个方法立即被执行。
监听器是用来干什么的
专门用于监听另一个Java对象的方法调用或属性改变 ,当被监听对象调用某个方法或者属性改变时,监听器的某个方法立即被执行。
监听器的分类
-
由于监听器就是实现特定接口的普通Java程序,其中接口(Listener)可以分为以下三类:
- 与ServletContext 有关:
- ServletContextListener :当某个javaweb类被创建或者销毁的时候,这个方法就会执行
- ServletContextAttributeListener :当存取context值的时候,这个类会被调用
- 与HttpSession有关:
- HttpSessionListener :
- HttpSessionAttributeListener
- HttpSessionActivationListener:
- HttpSessionBindingListener:
- 与ServletRequest有关:
- ServletRequestListener:
- ServletRequestAttributeListener:
- 与ServletContext 有关:
-
全局对象(application范围对象) :单个web站点的资源都共享一个servletContext类的实体**,通过该对象可以存取应用程序的全局对象以及初始化阶段的变量 。全局对象即为Application范围对象,其生命周期从容器启动至容器关闭,初始化变量是指在web.xml中由元素设定的变量,该变量的范围是Application范围
ServletContextListener接口
-
实现该接口的程序,当Java web应用程序启动时,会自动监听工作
-
应用程序启动时,先调用contextInitialized(ServletContextEvent sce)方法接受对应的ServletContextEvent事件 --> 当应用从容器中移除时,会自动调用contextDestoryed(ServletContextEvent sce)方法,sce可以调用getServletContext()方法取得ServletContext对象
-
package net; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class ServletContextListenerTest implements ServletContextListener { public ServletContextListenerTest() { // TODO Auto-generated constructor stub } public void contextDestroyed(ServletContextEvent sce) { sce.getServletContext(); System.out.println("当应用从容器中移除时调用该方法"); } public void contextInitialized(ServletContextEvent sce) { sce.getServletContext(); System.out.println("调用该方法,接受对应的ServletContextEvent事件"); } }
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8aALZHV4-1621741417965)(D:\JavaEE\图片\1621737115237.png)]
ServletContextAttributeListener接口
-
实现该接口的程序,能够监听Application范围的变化,当有随想存取全局范围时,该程序就会被调用。
-
当应用程序启动的时候,自动执行contextInitialized()–>搜索栏输入Test类的路径执行test类调用doget方法,向全局范围内存入数据,调用attributeAdded()方法–>选择服务器并关闭,执行contextDestoryed()方法
package net; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class ServletContextListenerTest implements ServletContextListener { public ServletContextListenerTest() { // TODO Auto-generated constructor stub } public void contextDestroyed(ServletContextEvent sce) { sce.getServletContext(); System.out.println("当应用从容器中移除时调用该方法"); } public void contextInitialized(ServletContextEvent sce) { sce.getServletContext(); System.out.println("调用该方法,接受对应的ServletContextEvent事件"); } }
-
package net; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.annotation.WebListener; @WebListener public class ServletContextAttributeListenerTest implements ServletContextAttributeListener { //构造方法 public ServletContextAttributeListenerTest() { } //全局对象的添加 public void attributeAdded(ServletContextAttributeEvent scae) { String key = scae.getName(); Object value = scae.getValue(); System.out.println("当存入全局对象的时候会自动调用这个方法,并取得你存入的key"+key+"和值value"+value); } //全局对象的移除 public void attributeRemoved(ServletContextAttributeEvent scae) { } public void attributeReplaced(ServletContextAttributeEvent scae) { String key = scae.getName(); Object value = scae.getValue(); System.out.println("当更新全局对象的时候会自动调用这个方法,并取得你存入的key"+key+"和值value"+value); System.out.println("更新后的值是"+scae.getServletContext().getAttribute("name")); } }
-
package net; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/test") public class Test extends HttpServlet { private static final long serialVersionUID = 1L; public Test() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getServletContext().setAttribute("name", "zhangzhang"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Np0sJR37-1621741417967)(D:\JavaEE\图片\1621737879115.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dpHquN6r-1621741417968)(D:\JavaEE\图片\1621737933504.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zl3gqI57-1621741417969)(D:\JavaEE\图片\1621737953754.png)]
-
attributeReplaced()方法中使用getValue()和getName()方法得到的值仍然是更新之前的值。我们可以使用全局事件对象来得到当前context的值。当程序发现application范围内没有该key时,执行attributeAdded()方法,当发现该key已经存在的时候,便会执行 attributeReplaced() 方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-awJUiPAH-1621741417970)(D:\JavaEE\图片\1621738767006.png)]
-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getServletContext().setAttribute("name", "zhangzhang"); request.getServletContext().setAttribute("name", "my god!"); request.getServletContext().removeAttribute("name"); }
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UlGqK3li-1621741417971)(C:\Users\Administrator\AppData\Local\Temp\1621738920580.png)]
HttpSessionListener
-
用来监听Session对象的创建和销毁,当Seesion对象产生,即**request.getSession()或销毁时,会自动调用sessionCreated()或sessionDestoryed()**方法
-
package net; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/test") public class Test extends HttpServlet { private static final long serialVersionUID = 1L; public Test() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute("123", "张大美女"); request.getSession().setAttribute("123", "123"); request.getSession().removeAttribute("123"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UblywfFp-1621741417972)(D:\JavaEE\图片\1621740548776.png)]
HttpSessionBindingEvent
-
方法:getName(),getSession(),getValue();
-
某个普通的类 实现HttpSessionBindingListener接口后,只要有该类的对象加入或者移除Session范围内 ,容器会分别调用下面两个方法:valueBound(HttpSessionBindingEvent e) valueUnBound(HttpSessionBindingEvent e)
-
•HttpSessionBindingListener接口是唯一不需要在web.xml中设定的Listener
-
package net; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; public class Student implements HttpSessionBindingListener{ @Override public void valueBound(HttpSessionBindingEvent event) { System.out.println("添加student对象到session中会调用该方法"); } @Override public void valueUnbound(HttpSessionBindingEvent event) { System.out.println("删除session中student对象时会调用该方法"); } }
-
package net; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/test") public class Test extends HttpServlet { private static final long serialVersionUID = 1L; public Test() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Student stu = new Student(); request.getSession().setAttribute("student", stu); request.getSession().removeAttribute("student"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
会先执行valueBound()方法–》sessionAttributeAdded()[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HofbRYWn-1621741417972)(D:\JavaEE\图片\1621741243680.png)]
例子
一 只可画图的画板
package com;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class MainFrame extends JFrame{
public boolean isDraw = false; //布尔类型变量用来说明是否可以画画
public int x1,y1,x,y; //定义坐标
public void drawLine() {
Graphics g = this.getContentPane().getGraphics();
g.setColor(Color.red);
g.drawLine(x, y, x1, y1); //Graphics中的抽象方法 public abstract void drawLine(int x1, int y1, int x2, int y2);
}
public MainFrame() {
MyMouseListener myMouseListener = new MyMouseListener(this);
MyMouseMotionListener myMouseMotionListener = new MyMouseMotionListener(this);
this.getContentPane().addMouseListener(myMouseListener);
this.getContentPane().addMouseMotionListener(myMouseMotionListener);
this.setSize(500, 500);
this.setVisible(true);
}
}
package com;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MyMouseListener implements MouseListener {
MainFrame mainFrame;
public MyMouseListener(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
@Override
public void mouseClicked(MouseEvent e) {//点击鼠标
}
@Override
public void mousePressed(MouseEvent e) {//按下鼠标
mainFrame.isDraw = true;
mainFrame.x = e.getX();
mainFrame.y = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {//释放鼠标
mainFrame.isDraw = false;
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
package com;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class MyMouseMotionListener implements MouseMotionListener {
MainFrame mainFrame;
public MyMouseMotionListener(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
@Override
public void mouseDragged(MouseEvent e) { //拖拽鼠标(按下左键并移动鼠标)
mainFrame.x1 = e.getX();
mainFrame.y1 = e.getY();
mainFrame.drawLine();
mainFrame.x = mainFrame.x1;
mainFrame.y = mainFrame.y1;
}
@Override
public void mouseMoved(MouseEvent e) { //移动鼠标
// TODO Auto-generated method stub
}
}
package com;
public class test {
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
}
}