java-web项目:用servlet监听器实现显示在线人数

1.创建一个监听器

package com.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
//使用监听器实现显示在线人数
public class MyServletSessionListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        // TODO 自动生成的方法存根
        ServletContext cx = event.getSession().getServletContext();//根据session对象获取当前容器的ServletContext对象
        Object objectlogincount = cx.getAttribute("logincount");//获取容器里面名字为logincount的对象
        String name = event.getName();
        if("is".equals(name)){//如果session增加的属性名字为is,表示成功登陆一个用户
            //System.out.println("登陆的用户名是:"+event.getValue());
            if(objectlogincount==null){//如果logincount为空,表示是第一个登陆
                cx.setAttribute("logincount", 1);
            }else{//表示已经有人登陆了
                int a = Integer.parseInt(objectlogincount.toString());//转换已经登陆的人数
                a++;
                cx.setAttribute("logincount", a);
            }
        }
        System.out.println("当前登陆的人数为:"+cx.getAttribute("logincount"));
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        // TODO 自动生成的方法存根
        
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        // TODO 自动生成的方法存根
        
    }

    
}

2.在web.xml中配置监听器

  <listener>
      <listener-class>com.listener.MyServletSessionListener</listener-class>
  </listener>

3.用LoginServ(servlet)进行测试

package com.serv;

import java.io.IOException;

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;
@WebServlet(urlPatterns={"/LoginServ"})
public class LoginServ extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO 自动生成的方法存根
        String name = req.getParameter("user");
        String pwd = req.getParameter("pwd");
        if(true){//假设用get方式提交,所有用户名密码都是正确的
            HttpSession session = req.getSession();
            session.setAttribute("is", name);//setAttribute() 方法添加指定的属性,并为其赋指定的值。如果这个指定的属性已存在,则仅设置/更改值。
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO 自动生成的方法存根
        doGet(req, resp);
    }
}

运行截图:

在浏览器上输入地址:

在myeclipse控制台会输出:

 

posted @ 2017-09-22 17:01  烟花盛典  阅读(875)  评论(0编辑  收藏  举报