Implementation class: onlineuser. Java
Package COM. alpha. onlineuser; </P> <p>/* <br/> * info: count the number of online users. <br/> * Date: 17:45:55 <br/> * Auth: javaalpha <br/> */</P> <p> Import javax. servlet. servletcontext; <br/> Import javax. servlet. HTTP. httpsession; <br/> Import javax. servlet. HTTP. httpsessionevent; <br/> Import javax. servlet. HTTP. httpsessionlistener; </P> <p> public class onlineuser implements httpsessionlistener <br/>{< br/> Public void sessioncreated (httpsessionevent event) <br/> {<br/> servletcontext SCT = event. getsession (). getservletcontext (); </P> <p> integer onlineuser = (integer) SCT. getattribute ("onlineuser"); <br/> If (null = onlineuser) {<br/> onlineuser = new INTEGER (1 ); <br/>} else {<br/> int COUNT = onlineuser. intvalue (); <br/> onlineuser = new INTEGER (count + 1); <br/>}< br/> SCT. setattribute ("onlineuser", onlineuser); <br/>}</P> <p> Public void sessiondestroyed (httpsessionevent event) <br/> {<br/> servletcontext SCT = event. getsession (). getservletcontext (); <br/> integer onlineuser = (integer) SCT. getattribute ("onlineuser"); <br/> If (null = onlineuser) {<br/> onlineuser = new INTEGER (0 ); <br/>} else {<br/> int COUNT = onlineuser. intvalue (); <br/> onlineuser = new INTEGER (count-1); <br/>}< br/> SCT. setattribute ("onlineuser", onlineuser); </P> <p> // destroy session <br/> // httpsession session = event. getsession (); <br/> // session. invalidate (); <br/>}< br/>}
JSP page: Test. jsp
<% @ Page Language = "Java" Import = "Java. util. *" pageencoding = "UTF-8" %> <br/> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <br/> <HTML> <br/> <body> <br/> current number of online users: <% = application. getattribute ("onlineuser") %> <br/> </body> <br/> </ptml> <br/>
Web. xml Listener Configuration:
<! -- Count the number of online users --> <br/> <listener-class> COM. webapp. onlineuser. onlineuser </listener-class> <br/> </listener>