监听器

Posted rory

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了监听器相关的知识,希望对你有一定的参考价值。

1.什么是监听器

  监听器主要用来监听request、session、application等对象的创建与销毁,以及属性的变化

2.监听器的使用

  a.创建监听器处理类

    普通的java类,实现Listner接口和AttributeListener接口

  b.在web.XML文件中配置监听器

完成:利用监听器,实现在线人数的统计

 

package com.zuxia.listener;

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

public class User implements HttpSessionBindingListener{
private String name;
private UserList ul = UserList.getInstance();
  public User() {

  }

  public User(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void valueBound(HttpSessionBindingEvent arg0) {
    ul.addUser(name);
  }

  public void valueUnbound(HttpSessionBindingEvent arg0) {

    ul.removeUser(name);
  }

}

 

package com.zuxia.listener;

import java.util.*;

public class UserList {
  private static final UserList userList = new UserList();
  private Vector<String> vec;
  public UserList() {
    vec = new Vector<String>();
  }

  /**
  * 得到在线用户实例
  * @return
  */
  public static UserList getInstance(){
    return userList;
  }

  /**
  * 用户登录时向在线用户列表中添加一个用户
  * @param name 登陆用户
  */
  public void addUser(String name){
    if (name != null) {
      vec.addElement(name);
    }
  }

  /**
  * 用户退出时,从在线用户列表中移除一个用户
  * @param name
  */
  public void removeUser(String name){
    if (name != null) {
      vec.remove(name);
    }
  }

  public Enumeration<String> getUserList(){
    return vec.elements();
  }

  /**
  * 返回当前用户个数
  * @return
  */
  public int getUserCount(){
    return vec.size();
  }
 }

 

package com.zuxia.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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.zuxia.listener.User;

@SuppressWarnings("serial")
public class LoginOutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    HttpSession session = request.getSession();
    User user= (User)session.getAttribute("user");
    session.invalidate();
    PrintWriter out = response.getWriter();
    out.print("<html><head><title>退出登陆</title></head><body>");
    out.print(user.getName()+",您已经退出登陆<br/>");
    out.print("<p><a href=‘login.jsp‘>重新登陆</a></p>");
    out.print("</body></html>");
    out.close();
  }
}

 

package com.zuxia.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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.zuxia.listener.User;
import com.zuxia.listener.UserList;

@SuppressWarnings("serial")
public class OnlineUser extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    String userName = request.getParameter("userName");
    String userPwd = request.getParameter("userPwd");
    if (userName == null || userName == "" || userPwd == null
      || userPwd == "") {
      response.sendRedirect("login.jsp");
    } else {
      HttpSession session = request.getSession();
      User user= (User)session.getAttribute("user");
      if (user == null || !userName.equals(user.getName())) {
        user = new User(userName);
        session.setAttribute("user", user);
      }

      out.print("欢迎用户<b>"+userName+"</b>登陆");
      UserList ul = UserList.getInstance();
      out.print("<br/>当前在线用户:<br/>");
      System.out.println(ul.getUserList());
      Enumeration<String> enums = ul.getUserList();
      int i = 0;
      while (enums.hasMoreElements()) {
        out.println(enums.nextElement());
        out.println("&nbsp;&nbsp;&nbsp;&nbsp;");
        i++;
      }
      out.println("<br/>当前在线用户数" + i);
      out.print("<p><a href=‘out‘>退出登陆</a></p>");
      out.close();
    }
  }
}

/*login.jsp*/

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

  <title>用户登录</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <style type="text/css">
    body{font-family: "微软雅黑";}
    #box{width: 230px ;margin: 100px auto; }
    span{line-height: 50px;}
    .txt{width:150px;height: 27px;}
    .btn{margin-left:25px;width:70px;height: 27px;}
  </style>
</head>

<body>
  <div id="box">
    <form action="OnlineUser" method="post">
      <span>用户名:</span><input class="txt" type="text"name="userName"/>
      <span>密&emsp;码:</span><input class="txt" type="password" name="userPwd"/>
      <input class="btn" type="submit" value="登陆"/>
      <input class="btn" type="reset" onclick="window.close()" value="取消"/>
    </form>
  </div>
</body>
</html>

 

/*web.xml*/

<?xml version="1.0" encoding="UTF-8"?>
  <web-app version="2.5"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>OnlineUser</servlet-name>
    <servlet-class>com.zuxia.servlet.OnlineUser</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>LoginOutServlet</servlet-name>
    <servlet-class>com.zuxia.servlet.LoginOutServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>OnlineUser</servlet-name>
    <url-pattern>/OnlineUser</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginOutServlet</servlet-name>
    <url-pattern>/out</url-pattern>
  </servlet-mapping>

  

  <listener>
    <listener-class>com.zuxia.listener.User</listener-class>
  </listener>


  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

以上是关于监听器的主要内容,如果未能解决你的问题,请参考以下文章

监听器监听器使用

监听器Listener

Servlet监听器详解及举例

Listener监听器

监听器

监听器