监听器

监听器Listener

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

被监听的对象(三个域对象 request,session,servletContext)
监听器:监听事件源对象, 事件源对象的状态的变化都会触发监听器 。
注册监听器:将监听器与事件源进行绑定。
响应行为:监听器监听到事件源的状态变化时,所涉及的功能代码(程序员编写代码)
按照被监听的对象划分:ServletRequest域 ;HttpSession域 ;ServletContext域。按照监听的内容分:监听域对象的创建与销毁的; 监听域对象的属性变化的。

image.png

image

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

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

编写一个监听器类去实现监听器接口
覆盖监听器的方法
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

自定义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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容