一种,单页面统计。就是说,只要点击这个页面就会统计一次。<%@ page contentType="text/html;charset=GB2312" %> <html> <head> <title> java计数器程序片 </title> </head> <body> <%!//在这种标记中定义的变量为全局变量 int count=0; synchronized void count(){ count++; } %> <% count(); out.println("这是第"+count+"个访问者!"); %> </body> </html>
2
第二中,是利用jsp的内置对象application进行统计。这个程序结果运行分析,也是访问一次页面统计一次。感觉还是不够好。真正满意的是浏览器打开网页,到关闭网页算一次,这样统计比较实际。 <%@ page contentType="text/html;charset=GB2312" %> <html> <head> <title> java计数器程序 </title> </head> <body> <% if(application.getAttribute("count")==null){ application.setAttribute("count",new Integer(0)); } Integer count=(Integer)application.getAttribute("count"); application.setAttribute("count",new Integer(count.intValue()+1)); count=(Integer)application.getAttribute("count"); %> <center>这是第<%=count.intValue()%>个访问者!</center> </body> </html>。
温馨提示:答案为网友推荐,仅供参考