监听器

简介: 监听器

监听器Listener


监听器就是监听某个对象的的状态变化的组件。监听器的相关概念事件源:

  • 被监听的对象(三个域对象 request,session,servletContext)
  • 监听器:监听事件源对象, 事件源对象的状态的变化都会触发监听器 。
  • 注册监听器:将监听器与事件源进行绑定。
  • 响应行为:监听器监听到事件源的状态变化时,所涉及的功能代码(程序员编写代码)

按照被监听的对象划分:ServletRequest域 ;HttpSession域 ;ServletContext域。按照监听的内容分:监听域对象的创建与销毁的; 监听域对象的属性变化的。


image.png

三大域对象的创建与销毁的监听器

ServletContextListener

监听ServletContext域的创建与销毁的监听器,Servlet域的生命周期:在服务器启动创建,服务器关闭时销毁;监听器的编写步骤:

  • 编写一个监听器类去实现监听器接口
  • 覆盖监听器的方法

ServletContextListener监听器的主要作用:

初始化的工作:初始化对象;初始化数据。

例子:MyServletContextListener.java

@WebListener()
public class MyServletContextListener implements ServletContextListener{
    @Override
    //监听context域对象的创建
    public void contextInitialized(ServletContextEvent sce) {
       System.out.println("context创建了....");
    }
    //监听context域对象的销毁
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("context销毁了....");
    }
}

HttpSessionListener

监听Httpsession域的创建与销毁的监听器。HttpSession对象的生命周期:第一次调用request.getSession时创建;销毁有以下几种情况(服务器关闭、session过期、 手动销毁)

1、HttpSessionListener的方法

/**
 * Created by yang on 2017/7/27.
 */
public class listenerDemo implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("session创建"+httpSessionEvent.getSession().getId());
    }
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("session销毁");
    }
}

创建session代码:

/**
 * Created by yang on 2017/7/24.
 */
public class SessionDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        request.getSession().setAttribute("code", "abc");
    }
}

当创建session时,监听器中的代码将执行。

ServletRequestListener

监听ServletRequest域创建与销毁的监听器。ServletRequest的生命周期:每一次请求都会创建request,请求结束则销毁。

1、ServletRequestListener的方法

/**
 * Created by yang on 2017/7/27.
 */
public class RequestListenerDemo implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        System.out.println("request被销毁了");
    }
    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        System.out.println("request被创建了");
    }
}

只要客户端发起请求,监听器中的代码就会被执行。

监听三大域对象的属性变化的

域对象的通用的方法

setAttribute(name,value)

触发添加属性的监听器的方法

触发修改属性的监听器的方法

removeAttribute(name):触发删除属性的监听器的方法

ServletContextAttibuteListener监听器

/**
 * Created by yang on 2017/7/27.
 */
public class ServletContextAttrDemo implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent scab) {
        //放到域中的属性
        System.out.println(scab.getName());//放到域中的name
        System.out.println(scab.getValue());//放到域中的value
    }
    @Override
    public void attributeRemoved(ServletContextAttributeEvent scab) {
        System.out.println(scab.getName());//删除的域中的name
        System.out.println(scab.getValue());//删除的域中的value
    }
    @Override
    public void attributeReplaced(ServletContextAttributeEvent scab) {
        System.out.println(scab.getName());//获得修改前的name
        System.out.println(scab.getValue());//获得修改前的value
    }
}

测试代码:

/**
 * Created by yang on 2017/7/27.
 */
public class ListenerTest extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context=getServletContext();
        context.setAttribute("aaa","bbb");
        context.setAttribute("aaa","ccc");
        context.removeAttribute("aaa");
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}

HttpSessionAttributeListener监听器(同上)

ServletRequestAriibuteListenr监听器(同上)


image.png


绑定与解绑的监听器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被绑定了");
    }
    @Override
    //解绑方法
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("person被解绑了");
    }
}

测试类:

public class TestPersonBindingServlet extends HttpServlet {
    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("zhangsanfeng");
        session.setAttribute("person", p);
        //将person对象从session中解绑
        session.removeAttribute("person");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


钝化与活化监听器


image.png


httpSession.setMaxInactiveInterval(-1);//永不销毁,服务器不死的情况下

自定义Customer 类

必须要实现:implements HttpSessionActivationListener,Serializable这两个接口

package www.test.domian;
import java.io.Serializable;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
public class Customer implements HttpSessionActivationListener,Serializable{
    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 sessionWillPassivate(HttpSessionEvent se) {
        System.out.println("customer被钝化了");
    }
    @Override
    //活化
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println("customer被活化了");
    }
}

配置文件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="webtest23" />
    </Manager>
</Context>

TestCustomerActiveServlet  测试钝化

package www.test.domian;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestCustomerActiveServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        //将customer放到session中
        Customer customer =new Customer();
        customer.setId("200");
        customer.setName("lucy");
        session.setAttribute("customer", customer);
        System.out.println("customer被放到session域中了");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

TestCustomerActiveServlet2 测试活化

package www.test.domian;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestCustomerActiveServlet2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //从session域中获得customer
        HttpSession 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);
    }
}

钝化后文件被保存的位置:

C:\Users\ttc\.IntelliJIdea2016.2\system\tomcat\Tomcat_8_0_21_markdownDemo\work\Catalina\localhost\ROOT\webtest23


1个月免登录


index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
欢迎您${userinfo.name}
<a href="LoginServlet.do?username=zhangsan">登录</a>
</body>
</html>

LoginServlet.java

@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet.do")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Customer customer = new Customer();
        customer.setName(username);
        request.getSession().setAttribute("userinfo",customer);
        Cookie cookie = new Cookie("JSESSIONID",request.getSession().getId());
        cookie.setMaxAge(60*60*24);
        response.addCookie(cookie);
    }
}

Customer.java

package www.test.domian;
import java.io.Serializable;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
public class Customer implements HttpSessionActivationListener,Serializable{
    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 sessionWillPassivate(HttpSessionEvent se) {
        System.out.println("customer被钝化了");
    }
    @Override
    //活化
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println("customer被活化了");
    }
}

配置文件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="webtest23" />
    </Manager>
</Context>


目录
相关文章
|
SQL Java 编译器
SQL 语言:嵌入式 SQL 和动态 SQL
SQL 语言:嵌入式 SQL 和动态 SQL
567 4
|
存储 Java Linux
TeamTalk - 蘑菇街开源的一款企业办公即时通信软件
TeamTalk 是蘑菇街开源的一款企业办公即时通信软件,最初是为自己内部沟通而做的 IM 工具。团队自己的介绍如下: 2013年我们蘑菇街从社区导购华丽转身时尚电商平台,为解决千万妹子和时尚卖家的沟通问题,我们开发了自己的即时通讯软件。既然已经有了用户使用的IM,为什么我们自己公司内部沟通还要用第三方的呢?因此就有了TT(TeamTalk)的雏形,现在蘑菇街内部的在线沟通全部通过TT来完成。随着TT功能的逐渐完善,我们决定把TT开源来回馈开源社区,希望国内的中小企业都能用上开源、免费、好用的IM工具!
1766 0
TeamTalk - 蘑菇街开源的一款企业办公即时通信软件
|
9月前
|
安全 Java 数据库连接
【反射】Java反射 全方位知识体系(附 应用场景 + 《八股文常考面试题》)
Java反射是运行时动态获取类元信息(构造器、方法、字段等)并操作对象的能力,核心为 Class对象。广泛应用于Spring、MyBatis等框架的IoC、AOP、ORM映射,以及注解处理、动态代理、SPI扩展等场景,兼具灵活性与解耦优势,但存在性能开销和安全风险。
858 10
|
3月前
|
Web App开发 人工智能 搜索推荐
信源权重低也能被AI引用?GEO实操指南
本文由Geo专家于磊基于实证研究,系统解答低权重网站在生成式引擎(GEO)时代的引用困境:揭示“信源等级”新内涵,指出低权重非劣势而是机会;用普林斯顿、斯坦福等权威研究证实——加证据、置结论、优结构比堆关键词更有效;提供6条可落地路径与GEO-16自查清单,助中小站点从“被检索”到“被引用”。
266 2
|
12月前
|
存储 缓存 网络协议
Linux 网络包的 “快递分拣”:从发送到接收的内核协作全景
本文以“快递分拣”为喻,详解Linux网络包从发送到接收的内核协作流程。通过系统调用、sk_buff封装、协议栈分层处理及硬/软中断协同,展现数据如何在应用层、内核与网卡间高效流转,揭示零拷贝、中断分工与分层设计等核心机制,呈现Linux网络栈精密高效的运作全景。(238字)
756 11
|
12月前
|
边缘计算 人工智能 监控
阿里云ESA是什么?边缘安全加速ESA 接入即安全、部署即全球、构建即智能
阿里云边缘安全加速ESA,基于全球3200+节点,提供加速、安全与边缘计算一体化服务。支持DDoS/CC防护、智能路由、边缘AI,具备高性能、高安全、易用性强等特点。分基础、标准、高级、企业版,流量防盗刷、HTTPS/WAF请求免费,首月可免费试用,助力业务全球加速与安全防护。
1491 8
|
文字识别 程序员 UED
Python + 腾讯云,多页PDF发票识别一键搞定!
程序员晚枫团队推出了基于Python和腾讯云的多页PDF发票识别功能!通过一行代码即可实现整本PDF发票的高效识别,并直接导出为Excel文件,极大提升工作效率。此次更新修复了仅识别第一页的bug,支持多页PDF完整识别。未来还将拓展更多票据类型、优化速度并加强平台合作。欢迎用户体验并提出建议,共同推动开源项目poocr的成长与进化!
793 7
|
传感器 监控 物联网
智慧家居环境监测与控制系统研发与应用的目标分析
- **背景**:随着物联网技术的发展和智能家居市场的快速增长,人们对居住环境的舒适性、安全性及能源使用效率的要求日益提高。 - **目的**:通过研发和应用智慧家居环境监测与控制系统,实现住宅环境中温度、湿度、空气质量等关键参数的有效管理和自动化调节。
1001 21
|
负载均衡 算法 Dubbo
提升集群吞吐量与稳定性的秘诀: Dubbo 自适应负载均衡与限流策略实现解析
提升集群吞吐量与稳定性的秘诀: Dubbo 自适应负载均衡与限流策略实现解析
1025 107
提升集群吞吐量与稳定性的秘诀: Dubbo 自适应负载均衡与限流策略实现解析
|
安全 Linux Shell
Kali渗透测试:使用Metasploit对Web应用的攻击
Kali渗透测试:使用Metasploit对Web应用的攻击
837 4