Servlet监听器

Java Web编程中则是在web.xml中配置所要监听的事件,由web容器在特定事件发生时自动的调用特定的实现监听器接口的类的特定方法。
servlet2.5版本设计了8个监听器,涉及了6种事件类型。
分别是4个监听器接口监听会话活动,两个监听器监听与ServletContext对象相关的事件,还有两个监听器接口监听与HttpServletRequest相关的事件。
主要四个是HttpSession接口:HttpSessionListener,HttpSessionAttributeListener,HttpSessionBindingListener以及HttpSessionOnActivationListener。

实例统计在线人数
新建一个Java类

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

/*
 * 当有一个新的用户访问这个Web应用的时候,Web容器自动调用sessionCreated()方法。
 * 当用户回话失效以后,Web容器又会自动调用sessionDestroyed()方法。
 * 
 * */
public class CounterListener implements HttpSessionListener {

    private static long onlineNumber  = 0;

    public static long getOnlineNumber(){
        return onlineNumber;
    }

    public void sessionCreated(HttpSessionEvent se){
        onlineNumber++;
    }
    public void sessionDestroyed(HttpSessionEvent se){
        onlineNumber--;
    }
}

该类实现了HttpSessionLisener接口。
编辑Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">
  <display-name></display-name> 

  <listener>
    <listener-class>
    webbook.chapter12.CounterListener
    </listener-class>
  </listener>

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

编辑display.jsp

<%@ page language="java" import="java.util.*"  pageEncoding="UTF-8"%>

<%
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>My JSP 'display.jsp' starting page</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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>

    当前应用一共有<%=webbook.chapter12.CounterListener.getOnlineNumber()%>人在线
  </body>
</html>

注意jsp文件导入import包名类名,否则编译不通过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值