Session、SessionListener、在线人数统计

Listener_OnlineCount.java

 package com.wzucxd.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.wzucxd.count.CountNum; public class Listener_OnlineCount implements HttpSessionListener { public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext application = session.getServletContext(); if (session.isNew()) { CountNum.addNum(); application.setAttribute("num", CountNum.getNum()); } } public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext application = session.getServletContext(); if (CountNum.getNum() > 0) { CountNum.minNum(); application.setAttribute("num", CountNum.getNum()); } } }

 

CountNum.java

package com.wzucxd.count; public class CountNum { private static int i=0; public static int getNum() { return i; } public static void addNum() { i++; } public static void minNum() { i--; } }

 

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <%@taglib prefix="c" uri="/WEB-INF/tld/c-rt.tld"%> <%@page import="com.wzucxd.count.CountNum" %> <% 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 'index.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" mce_href="styles.css"> --> </head> <body> <c:out value="${applicationScope.num}"></c:out><br><br></body> </html>

你可能感兴趣的:(html,session,String,application,import,stylesheet)