码迷,mamicode.com
首页 > 其他好文 > 详细

监听器Listener

时间:2018-05-19 18:26:10      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:val   back   lang   god   实现   request   out   round   getattr   

1.ServletContext监听器:

用来监听ServletContext的创建与销毁

步骤:

a、编写一个监听器类去实现监听器接口

b、覆盖监听器的方法

c、需要在web.xml中进行配置---注册

public class ServletContext implements ServletContextListener {

    public ServletContext() {
        // TODO Auto-generated constructor stub
    }

    public void contextDestroyed(ServletContextEvent sce)  { 
        System.out.println("web应用销毁");
    }

    public void contextInitialized(ServletContextEvent sce)  { 
         System.out.println("web应用初始化");
         Timer t = new Timer();
         t.scheduleAtFixedRate(new TimerTask() {//在ServletContext初始化时,添加定时任务
             @Override
            public void run() {
                System.out.println("利息增加");
            }
             
         },new Date(), 5000);//执行的任务,开始时间,间隔
    }
    
}

2.ServletContextAttributeListener ServletContext属性监听

监听ServletContext中的属性有变化(增、删、改)

public class ServletContextAttr implements ServletContextAttributeListener {

    public ServletContextAttr() {
        // TODO Auto-generated constructor stub
    }

    public void attributeAdded(ServletContextAttributeEvent scae)  { 
        System.out.println("增加属性 ");
        System.out.println("属性是" + scae.getName());
        System.out.println("值是" + scae.getValue());
    }

    public void attributeRemoved(ServletContextAttributeEvent scae)  { 
         System.out.println("属性移除");
    }

    public void attributeReplaced(ServletContextAttributeEvent scae)  { 
        System.out.println("属性替换");
    }
    
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        application.setAttribute("name","god");//添加ServletContext属性
        application.setAttribute("name", "wish");//替换属性
        application.removeAttribute("name");//移除属性
    %>
</body>
</html>

3.Session监听器

用来监听Session的创建与销毁

public class Session implements HttpSessionListener {

    public Session() {
        // TODO Auto-generated constructor stub
    }

    public void sessionCreated(HttpSessionEvent se)  { 
         String s = se.getSession().getId();
         System.out.println("session被创建,ID为:"+s);
    }

    public void sessionDestroyed(HttpSessionEvent se)  { 
         System.out.println("session被销毁);
    }
    
}

 在线人数统计:

public class OnlineNumberListener implements HttpSessionListener{

    @Override
    public void sessionCreated(HttpSessionEvent e) {
        ServletContext application = e.getSession().getServletContext();
        Integer onlinenumber = (Integer)application.getAttribute("onlinenumber");
        if(onlinenumber==null) {
            onlinenumber = 0;
        }
        onlinenumber++;
        application.setAttribute("onlinenumber", onlinenumber);
        System.out.println("新增一位在线用户");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent e) {
        ServletContext application = e.getSession().getServletContext();
         
        Integer online_number = (Integer) application.getAttribute("online_number");
 
        if(null==online_number){
            online_number = 0;
        }
        else
            online_number--;
        application.setAttribute("online_number", online_number);
        System.out.println("一位用户离线");
    }

}

 4.Request监听器

public class Request implements ServletRequestListener {

    public Request() {
        // TODO Auto-generated constructor stub
    }

    public void requestDestroyed(ServletRequestEvent sre)  { 
         System.out.println("请求销毁");
    }

    public void requestInitialized(ServletRequestEvent sre)  { 
        String p =  sre.getServletRequest().getParameter("name");
        System.out.println("收到请求,请求值为:"+p);
    }
    
}

总结:ServletContext Session Request 都可以实现各自的Listener接口,也可以实现各自的AttributeListener接口,重写方法即可。

 5.绑定监听

HttpSessionBindingListener接口,可以监听对象是否被绑定至Session内

public class Person implements HttpSessionBindingListener{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("Person对象绑定至session域");
    }
    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("Person对象从session域中解绑");
    }
}
HttpSession session = request.getSession();
Person p = new Person();
session.setAttribute("person", p);
session.removeAttribute("person");

6.钝化与活化

Session对象长期不使用时可以写入到本地磁盘,即钝化,下次访问时在写回session中,即活化

需要同时实现HttpSessionActivationListener,Serializable两个接口

public class Car implements HttpSessionActivationListener,Serializable{
    private static final long serialVersionUID = 1L;
    private String color;
    private String brand;
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        System.out.println("Car被钝化");
    }
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println("Car被活化");
    }
}
HttpSession session = request.getSession();
Car c = new Car();
c.setColor("red");
session.setAttribute("car", c);
System.out.println("Car被添加到session中");

自定义配置:

在WebContent/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="demo" />
 </Manager>
</Context>

监听器Listener

标签:val   back   lang   god   实现   request   out   round   getattr   

原文地址:https://www.cnblogs.com/whwjava/p/9060080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!