[Java]监听器(Listener)
过滤器(Filter)https://blog.csdn.net/m0_71229255/article/details/130246404?spm=1001.2014.3001.5501
一 : Listener监听器简述
监听器就是监听某个对象的的状态变化的组件
监听器的相关概念:
-
事件源:
被监听的对象 ----- 三个域对象request
session
servletContext
-
监听器 :
监听事件源对象的状态的变化都会触发监听器 -
注册监听器 :
将监听器与事件源进行绑定 -
响应行为 :
监听器监听到事件源的状态变化时 所涉及的功能代码
二 : 监听器的种类
- 按照被监听的对象划分:ServletRequest域 HttpSession域 ServletContext域
- 监听的内容分:监听域对象的创建与销毁的 监听域对象的属性变化的
................................... | ServletContext域 | HttpSession域 | ServletRequest域 |
---|---|---|---|
域对象的创建于销毁 | servletContextListener | HttpSessionListener | ServletRequestListener |
域对象内的属性的变化 | ServletContextAttributeListener | HttpSessionAttributeListener | ServletRequestAttributeListener |
三 : 监听三大域对象的创建与销毁的监听器
( 1 )监听ServletContext域的创建与销毁的监听器ServletContextListener
监听编写步骤 :
① : 编写一个监听器类去实现监听器接口
public class MyServletContextListener implements ServletContextListener
② : 覆盖监听器的方法
@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println("context创建了....");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println("context销毁了");}
③ : 在web.xml中进行配置
<listener><listener-class>com.TianTian.atrribute.MyServletContextAttributeListener</listener-class></listener>
ServletContextListener监听器的主要作用
① : 初始化的工作 ,初始化对象,初始化数据,加载数据驱动,连接池的初始化
② : 加载一下初始化的配置文件,如Spring的配置文件
③ : 任务调度---定时器---Timer/TimerTask
Timer timer = new Timer();//task:任务 firstTime:第一次执行时间 period:间隔执行时间//timer.scheduleAtFixedRate(task, firstTime, period);String currentTime = "2018-10-11 18:11:00";SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");Date parse = null;try {parse = format.parse(currentTime);} catch (ParseException e) {e.printStackTrace();}timer.scheduleAtFixedRate(new TimerTask() {@Overridepublic void run() {System.out.println("do something.....");}} , parse, 24*60*60*1000);
( 2 )监听HttpSession域的创建与销毁的监听器HttpSessionListener
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;public class MySessionListener implements HttpSessionListener{@Overridepublic void sessionCreated(HttpSessionEvent se) {System.out.println("sessionId : " + se.getSession().getId());}@Overridepublic void sessionDestroyed(HttpSessionEvent se) {}}
( 3 )监听ServletRequest域创建与销毁的监听器ServletRequestListener
public class MyServletRequestListener implements ServletRequestListener{@Overridepublic void requestDestroyed(ServletRequestEvent sre) {System.out.println("销毁");}@Overridepublic void requestInitialized(ServletRequestEvent sre) {System.out.println("创建");}
}
四 : 监听三大域对象的属性变化的
( 1 )域对象的通用方法
-
setAttribute(name,value) 触发添加属性/修改属性的监听器的方法
-
getAttribute(name) 触发获取属性的监听方法
-
removeAttribute(name) 触发删除属性的监听器的方法
( 2 )ServletContextAttributeLisener监听器
public class MyServletContextAttributeListener implements ServletContextAttributeListener{@Overridepublic void attributeAdded(ServletContextAttributeEvent scab) {//放到域中的属性System.out.println("+++++监听放入");System.out.println(scab.getName());//放到域中的nameSystem.out.println(scab.getValue());//放到域中的value}@Overridepublic void attributeRemoved(ServletContextAttributeEvent scab) {System.out.println("+++++监听修改");System.out.println(scab.getName());//删除的域中的nameSystem.out.println(scab.getValue());//删除的域中的value}@Overridepublic void attributeReplaced(ServletContextAttributeEvent scab) {System.out.println("+++++监听移除");System.out.println(scab.getName());//获得修改前的nameSystem.out.println(scab.getValue());//获得修改前的value}
测试
public class TestMyServletContextAttributeListener extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletContext context = this.getServletContext();//存数据context.setAttribute("name", "美美");//改数据context.setAttribute("name", "可可");//删除数据context.removeAttribute("name");} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
(3) HttpSessionAttributeListener监听器(同上)
(4) ServletRequestAriibuteListenr监听器(同上)
五 : 对象感知监听器
即将要被绑定到Session中的对象有几种状态
- 绑定状态 : 就一个对象被放到session域中
- 解绑状态 : 被绑定的对象从session域中移除了
- 钝化状态 : 是将session内存中的对象持久化( 序列化)到磁盘
- 活化状态 : 就是将磁盘上的对象再次恢复到session内存中
(1) 绑定与解绑的监听器HttpSessionBindingListener
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;public class Person implements HttpSessionBindingListener{private String id;private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Override//绑定public void valueBound(HttpSessionBindingEvent event) {System.out.println("person被绑定了");Person per = (Person)event.getValue();System.out.println(per.getName());}@Override//解除绑定public void valueUnbound(HttpSessionBindingEvent event) {System.out.println("person被解绑了");}
}
测试
public class TestPersonBindingServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession();//将person对象绑到session中Person p = new Person();p.setId("100");p.setName("思思");session.setAttribute("person", p);//将person对象从session中解绑session.removeAttribute("person");}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
person被绑定了
思思
person被解绑了
(2) 钝化与活化的监听器HttpSessionActivationListener
可以通过配置文件,指定对象钝化时间---对象多长时间不用被敦化
在META-INF下创建一个context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context><!-- maxIdleSwap:session中的对象多长时间不使用就钝化 --><!-- directory:钝化后的对象的文件写到磁盘的哪个目录下 配置钝化的对象文件在 work/catalina/localhost/钝化文件 --><Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1"><Store className="org.apache.catalina.session.FileStore" directory="tiantian" /></Manager>
</Context>
创建customer类
public class Customer implements HttpSessionActivationListener,Serializable{/*** */private static final long serialVersionUID = 1L;private String id;private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic void sessionWillPassivate(HttpSessionEvent se) {//钝化System.out.println("customer被顿化了");}@Overridepublic void sessionDidActivate(HttpSessionEvent se) {//激活System.out.println("customer被活化了");}
}
测试
存
ublic class TestCustomerServlet1 extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession();Customer customer = new Customer();customer.setId("200");customer.setName("狗狗");session.setAttribute("customer", customer);System.out.println("customer被放到session域中了");}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}
}
活化取出
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//从session域中获得customerHttpSession session = request.getSession();Customer customer = (Customer) session.getAttribute("customer");System.out.println(customer.getName());}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}