美文网首页
浅谈Servlet技术中的Listener起到的作用

浅谈Servlet技术中的Listener起到的作用

作者: 值得一看的喵 | 来源:发表于2017-10-09 12:01 被阅读0次

    Listener是在servlet2.3中加入的,主要用于对Session,request,context等进行监控。使用Listener需要实现响应的接口。触发Listener事件的时候,tomcat会自动调用Listener的方法。在web.xml中配置标签,一般要配置在标签前面,可配置多个,同一种类型也可配置多个com.xxx.xxx.ImplementListenerservlet2.5的规范中共有8中Listener,分别监听session,context,request等的创建和销毁,属性变化等。

    常用的监听接口: 监听对象HttpSessionListener :监听HttpSession的操作,监听session的创建和销毁。 可用于收集在线着信息ServletRequestListener:监听request的创建和销毁。ServletContextListener:监听context的创建和销毁。  

    启动时获取web.xml里配置的初始化参数监听对象的属性HttpSessionAttributeListener :ServletContextAttributeListener :ServletRequestAttributeListener :监听session内的对象HttpSessionBindingListener:对象被放到session里执行valueBound(),对象移除时执行valueUnbound()。对象必须实现该lisener接口。HttpSessionActivationListener:服务器关闭时,会将session里的内容保存到硬盘上,这个过程叫做钝化。服务器重启时,会将session内容从硬盘上重新加载。

    下面为大家分享一个Listener的应用实例:利用HttpSessionListener统计最多在线用户人数

    import java.text.DateFormat;

    import java.text.SimpleDateFormat;

    import java.util.Date;

    import javax.servlet.

    ServletContext;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;public class HttpSessionListenerImpl implements HttpSessionListener {    public void sessionCreated(HttpSessionEvent event) {        ServletContext app = event.getSession().getServletContext();        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());        count++;        app.setAttribute("onLineCount", count);        int maxOnLineCount = Integer.parseInt(app.getAttribute("maxOnLineCount").toString());        if (count > maxOnLineCount) {            //记录最多人数是多少            app.setAttribute("maxOnLineCount", count);            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            //记录在那个时刻达到上限            app.setAttribute("date", df.format(new Date()));        }    }    //session注销、超时时候调用,停止tomcat不会调用    public void sessionDestroyed(HttpSessionEvent event) {        ServletContext app = event.getSession().getServletContext();        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());        count--;        app.setAttribute("onLineCount", count);        }

    }

    相关文章

      网友评论

          本文标题:浅谈Servlet技术中的Listener起到的作用

          本文链接:https://www.haomeiwen.com/subject/ffnuyxtx.html