HttpSessionListener是個session監聽器
代碼如下
首先建一個監聽類CountLineListener
[java]
packagecom
importjavax
importjavax
importjavax
publicclassCountLineListenerimplementsHttpSessionListener{
/***********
*創建session時調用
*/
publicvoidsessionCreated(HttpSessionEventevent){
System
ServletContextcontext=event
Integercount=(Integer)context
if(count==null){
count=newInteger(
}else{
intco=count
count=newInteger(co+
}
System
context
}
/************
*銷毀session時調用
*/
publicvoidsessionDestroyed(HttpSessionEventevent){
System
ServletContextcontext=event
Integercount=(Integer)context
intco=count
count=newInteger(co
context
System
}
}
監聽類寫好了
[java]
<listener>
<listener
</listener>
針對以上可以結合servlet寫個小例子
(
[html]
<%@pagelanguage=
<!DOCTYPEHTMLPUBLIC
<html>
<head>
<title>MyJSP
<metahttp
<metahttp
<metahttp
<metahttp
<metahttp
</head>
<body>
<formmethod=
<inputtype=
<br/><inputtype=
</form>
</body>
</html>
點擊登錄
(
[java]
packagecom
importjava
importjavax
importjavax
importjavax
importjavax
publicclassMyServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest
throwsServletException
this
}
publicvoiddoPost(HttpServletRequestrequest
throwsServletException
Stringuser=request
request
request
}
}
登錄就跳到首頁index
[html]
<%@pagelanguage=
<!DOCTYPEHTMLPUBLIC
<html>
<head>
<title>MyJSP
<metahttp
<metahttp
<metahttp
<metahttp
<metahttp
</head>
<body>
這裡是首頁
<%
ServletContextcontext=session
Integercount=(Integer)context
%>
<%=count%>
<br/>
當前用戶
</body>
</html>
這樣就簡單實現統計當前在線人數的效果了
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26031.html