1. 程式人生 > >通過HttpSessionListener監聽介面實現對當前線上人數的監聽

通過HttpSessionListener監聽介面實現對當前線上人數的監聽

程式設計:通過HttpSessionListener監聽介面實現對當前線上人數的監聽

要求:

(1) 編寫一個類實現HttpSessionListener介面,在該介面的public void sessionCreated(HttpSessionEvent se)方法中,宣告一個變數用於記錄線上的人數,並將其以屬性的形式儲存在ServletContext物件中。

(2) 在web.xml中對該監聽器進行配置。

(3) 編寫一個JSP頁面,用於取得application物件中的屬性值,並將其顯示在頁面上。

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<html>
	<head>
	</head>

	<body>
		<%  application.getAttribute("a"); %>
	</body>
</html>


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<listener>
		<listener-class>com.mars.SessionCount</listener-class>
	</listener>
</web-app>

package com.mars;

import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionCount implements HttpSessionListener {
	int a = 0;
	public void sessionCreated(HttpSessionEvent hse) {
		a++;
		ServletContext application = hse.getSession().getServletContext();
		application.setAttribute("a",new Integer(a));

	}

	public void sessionDestroyed(HttpSessionEvent red) {

	}


}