Fork me on GitHub

监听器(web基础学习笔记二十二)

一、监听器

监听器是一个专门用于对其他对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生情况时,立即采取相应的行动。监听器其实就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法立即被执行。

二、监听器统计在线人数--HttpSessionListener实现

package com.pb.news.listenter;

public class OnlineCounter {
    public static long ONLINE_USER_COUNT=0;
    public static long getonline(){
        return ONLINE_USER_COUNT;
    }

    public static void raise() {
        ONLINE_USER_COUNT++;
    }

    public static void reduce() {
        ONLINE_USER_COUNT--;
    }
}
package com.pb.news.listenter;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class OnlineCounterListener
 *
 */
public class OnlineCounterListener implements HttpSessionListener {

    /**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent arg0)  { 
         // TODO Auto-generated method stub
        //session创建里用户加1
        OnlineCounter.raise();
    }

    /**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
        //session销毁里里用户减1
        OnlineCounter.reduce();
    }
    
}

只需要在页面中写入

在线人数:<%=OnlineCounter.getonline() %>

三、监听器统计在线人数--HttpSessionBindingListener实现绑定用户登录查询在线人数

 创建静态变量类

package com.pb.news.constants;

public class Constants {
//统计在线人线人数静态常量
    public static int ONLINE_USER_COUNT=0;
}

创建用户类来实现-接口-HttpSessionBindingListener

package com.pb.news.listenter;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import com.pb.news.constants.Constants;

/**
 * Application Lifecycle Listener implementation class UserLoginCount
 *
 */
public class UserLoginCount implements HttpSessionBindingListener {
    private int id;                  //用户id;                        
    private String username;       //用户姓名                     
    private String password;       //用户密码                      
    private String email;          //用户邮箱         
    private int usertype;             //用户类型      
    
    //getter和setter方法
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = 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 getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getUsertype() {
        return usertype;
    }
    public void setUsertype(int usertype) {
        this.usertype = usertype;
    }

    /**
     * Default constructor. 
     */
    public UserLoginCount() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
     */
    public void valueBound(HttpSessionBindingEvent arg0)  { 
        Constants.ONLINE_USER_COUNT++;
    }

    /**
     * @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
     */
    public void valueUnbound(HttpSessionBindingEvent arg0)  { 
        Constants.ONLINE_USER_COUNT--;
    }
    
}

创建登录servlet类

package com.pb.news.web.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.pb.news.dao.impl.UsersDaoImpl;
import com.pb.news.entity.Users;
import com.pb.news.listenter.UserLoginCount;
import com.pb.news.service.impl.UsersServiceImpl;

/**
 * Servlet implementation class UserLoginServlet
 */
public class UserLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.setCharacterEncoding("utf-8");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        UsersServiceImpl usersService=new UsersServiceImpl();
        UsersDaoImpl usersDao=new UsersDaoImpl();
        usersService.setUsersDao(usersDao);
        boolean flag=usersService.login(username, password);
        if(flag==true){
            //request.getSession().setAttribute("user", username);
            //创建HttpSessio对象
            /*Users users=new Users();
            users.setUsername(username);
            users.setPassword(password);*/
            UserLoginCount users= new UserLoginCount();
            users.setUsername(username);
            users.setPassword(password);
            HttpSession s=request.getSession();
            s.setAttribute("user", users);
            //s.setAttribute("pwd", password);
            //request.getRequestDispatcher("jsp/index.jsp").forward(request, response);
            response.sendRedirect("jsp/index.jsp");
            
        }else{
            request.setAttribute("msg", "用户名或者密码不正确");
            RequestDispatcher rd=request.getRequestDispatcher("jsp/userLogin.jsp");
            rd.forward(request, response);
            //request.getRequestDispatcher("jsp/userLogin.jsp").forward(request, response);
            //response.sendRedirect("jsp/userLogin.jsp");
        }
        
    }

}

在要显示的页面显示

已登录用户:<%=com.pb.news.constants.Constants.ONLINE_USER_COUNT %> 

相比较,第一种更简洁,这里可能还有理简单的输出,暂时没发现

四、监听器统计在线人数--HttpSessionListener实现

package com.pb.news.web.servlet;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class UserCountListener implements HttpSessionListener {
    private int count = 0;

    public void sessionCreated(HttpSessionEvent se) {
        // TODO Auto-generated method stub
        //人数加1
        count++;
        setContext(se);

    }

    public void sessionDestroyed(HttpSessionEvent se) {
        // TODO Auto-generated method stub
        //人数减1
         count--;
         setContext(se);


    }
    private void setContext(HttpSessionEvent se){
        se.getSession().getServletContext().setAttribute("userCount",new Integer(count));
    }

}
创建UserCountListener监听器,注意web.xml中要有:
<listener>
        <listener-class>com.pb.news.web.servlet.UserCountListener</listener-class>
</listener>

创建监听器后,可以在需要显示人数的页面加入下面的语句:
Object userCount=session.getServletContext().getAttribute("userCount");
out.print(userCount.toString());

 五、不需要登录统计在线人数

package com.pb.listenter;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class CountListenter
 *
 */
@WebListener
public class CountListenter implements HttpSessionListener {
    //private int count=0;
    /**
     * Default constructor. 
     */
    public CountListenter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 创建seesion+1
     */
    public void sessionCreated(HttpSessionEvent se)  { 
         // TODO Auto-generated method stub
        ServletContext context=se.getSession().getServletContext();
        Integer count=(Integer) context.getAttribute("count");
        if(count==null){
            //count=new Integer(1);
            context.setAttribute("count", 1);
        }else{
            count++;
            context.setAttribute("count", count);
        }
        
        
    }

    /**
     * 销毁session时次数-1
     */
    public void sessionDestroyed(HttpSessionEvent se)  { 
         // TODO Auto-generated method stub
        ServletContext context=se.getSession().getServletContext();
        Integer count=(Integer) context.getAttribute("count");
        count--;
        context.setAttribute("count", count);
        
    }
    
}

在需要显示的页面输入以下代码显示

<%
ServletContext context=session.getServletContext();
Integer count=(Integer)context.getAttribute("count");
%>
  <%=count%>

 

posted @ 2015-02-03 20:30  森林森  阅读(943)  评论(0编辑  收藏  举报