java监听器笔记

监听器Listener

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

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

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

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

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监听器(同上)

绑定与解绑的监听器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);
    }
}
复制代码

钝化与活化监听器

自定义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>
复制代码

监听器应用举例---统计网站在线人数

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" session="false" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
<a href="login.jsp">登录</a>
<a href="ShowUser">显示在线用户</a>
  </body>
</html>
复制代码

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java"  session="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<center>
    <h3>用户登录</h3>
</center>
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
    <table border="1" width="550px" cellpadding="0" cellspacing="0" align="center">
        <tr>
            <td height="35" align="center">用户名</td>
            <td>
                &nbsp;&nbsp;&nbsp;
                <input type="text" name="username"/>
            </td>
        </tr>
        <tr>
            <td height="35" align="center">密 &nbsp; 码</td>
            <td>
                &nbsp;&nbsp;&nbsp;
                <input type="password" name="password"/>
            </td>
        </tr>
        <tr>
            <td height="35" colspan="2" align="center">
                <input type="submit" value="登录"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>
复制代码

User.java

public class User{

    private String username;
    private String password;
    private String id;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


}
复制代码

OnlineUser.java

public class OnlineUser {
    private OnlineUser() {}
    private static OnlineUser instance = new OnlineUser ();
    public static OnlineUser getInstance() {
        return instance;
    }
    private Map userMap = new HashMap();
    //将用户添加到列表中
    public void addUser(User user){
        userMap.put (user.getId (),user.getUsername ());
    }
    //将用户移除列表
    public void removeUser(String uid){
        userMap.remove (uid);
    }
    //返回用户列表
    public Map getOnlineUser() {
        return userMap;
    }
}
复制代码

LoginServlet.java

@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding ("utf-8");
        response.setContentType ("text/html;charset=utf-8");
        String username = request.getParameter ("username");
        String password = request.getParameter ("password");
        if (username !=null && !username.isEmpty()){

            HttpSession httpSession = request.getSession();
            httpSession.setAttribute("username",username);

            //登录成功
            request.setAttribute ("users",OnlineUser.getInstance().getOnlineUser());
            httpSession.setMaxInactiveInterval(20);
            request.getRequestDispatcher ("/showuser.jsp").forward (request,response);
        } else {
            request.setAttribute ("errorMsg","用户名或密码错误");
            request.getRequestDispatcher ("/login.jsp").forward (request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost (request,response);
    }
}

复制代码

showuser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java"   %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:choose>
    <c:when test="${sessionScope.username==null}">
        <a href="${pageContext.request.contextPath}/login.jsp">登录</a>
        <br/>
    </c:when>
    <c:otherwise>
        欢迎你,${sessionScope.username}
        <a href="${pageContext.request.contextPath}/LogoutServlet">退出</a>
    </c:otherwise>
</c:choose>
<hr/>
在线用户列表
<br/>
    <c:forEach var="user" items="${requestScope.users}">
        ${user.value}
     </c:forEach>
</body>
</html>
复制代码

LogoutServlet.java

package com.neusoft.servlet;

import com.neusoft.util.OnlineUser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "LogoutServlet",urlPatterns = "/LogoutServlet")
public class LogoutServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding ("utf-8");
        response.setContentType ("text/html;charset=utf-8");
        HttpSession httpSession = request.getSession(false);
        if(httpSession!=null)
        {

            httpSession.invalidate();
        }

        request.setAttribute ("users",OnlineUser.getInstance().getOnlineUser());
        request.getRequestDispatcher ("/showuser.jsp").forward (request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost (request,response);
    }
}
复制代码

ShowUserServlet.java

@WebServlet(name = "ShowUserServlet",urlPatterns = "/ShowUser")
public class ShowUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession httpSession = request.getSession();

        request.setAttribute ("users",OnlineUser.getInstance().getOnlineUser());
        request.getRequestDispatcher ("/showuser.jsp").forward (request,response);
    }
}

复制代码

SessionListener.java(重点)

@WebListener()
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {

    // Public constructor is required by servlet spec
    public SessionListener() {
    }

     // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    public void sessionCreated(HttpSessionEvent se) {
      /* Session is created. */
    }

    public void sessionDestroyed(HttpSessionEvent se) {
      /* Session is destroyed. */
        System.out.println("sessionDestroyed");
        if(OnlineUser.getInstance().getOnlineUser().containsKey(se.getSession().getId()))
        {
            OnlineUser.getInstance().removeUser(se.getSession().getId());
        }
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------

    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
        System.out.println("attributeAdded");
      if(sbe.getName().equals("username"))
      {
          User user = new User();
          user.setId(sbe.getSession().getId());
          user.setUsername((String)sbe.getValue());
          OnlineUser.getInstance().addUser(user);
      }
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
        System.out.println("attributeRemoved");
      if(OnlineUser.getInstance().getOnlineUser().containsKey(sbe.getSession().getId()))
      {
          OnlineUser.getInstance().removeUser(sbe.getSession().getId());
      }
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attibute
         is replaced in a session.
      */
    }
}

复制代码

转载于:https://juejin.im/post/5ad6d656f265da238e0e43e7

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值