Jsp Tutorial: use application to count the number of online users
<% @ 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>
<Title> application </title>
</Head>
<Body>
<%!
Integer number ;//
Synchronized void numberVisiter ()
{
ServletContext application = getServletContext ();
Integer num = (Integer) application. getAttribute ("count ");
If (num = null) // if it is the first visitor
{
Num = new Integer (1 );
Application. setAttribute ("count", num );
}
Else
{
Num = new Integer (num. intValue () + 1 );
Application. setAttribute ("count", num );
}
}
%>
<%
If (session. isNew ())
{
NumberVisiter ();
Integer number = (Integer) application. getAttribute ("count ");
}
%>
<P>
<Font size = "2" color = "blue"> simple page access counters </font>
</P>
<P>
<Font size = "2" color = "#000000" type = "codeph" text = "/codeph">
Welcome to this page. You are <% = number %> Users
</Font>
</P>
</Body>
</Html>