Java Web 监听器

92 阅读1分钟

监听各种变化(session,EL表达式,。。。)

大致流程

  • 实现需要监听的对应接口(Listener)
  • 重写接口方法
  • web.xml中配置

样例

  • 统计session个数

实现Listener接口

public class OnlineCountL implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer count = (Integer) context.getAttribute("sessionNum");
        if (count == null) {
            count = new Integer(1);
        } else {
            int i = count.intValue();
            count = new Integer(i++);
        }
        context.setAttribute("sessionNum", count);
        System.out.println(se.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer count = (Integer) context.getAttribute("sessionNum");
        if (count == null) {
            count = new Integer(0);
        } else {
            int i = count.intValue();
            count = new Integer(i--);
        }
        context.setAttribute("sessionNum", count);
    }
}

前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>有<span style="color: blue"><%=application.getAttribute("sessionNum")%></span>个session在维持会话。</>
</body>
</html>

配置web.xml

<listener>
    <listener-class>listener.OnlineCountL</listener-class>
  </listener>

遇到的错误

  • getAttribute("sessionNum");返回值是Object。且浏览器还没打开之前java就已经加载好了,返回值会是null。
  • 如果写成int count = (int) context.getAttribute("sessionNum");就会出现int=null的情况,然后就会报错

=========================================