版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41061455/article/details/82219724
Application对象是JSP的一个内建对象。当服务器启动时,该对象会被自动创建,直到服务器关闭。并且在这期间可以被多个用户共同使用。这是不同于session对象的。本篇将使用Application对象实现网站计数器,程序运行结果如下所示。
遇到的问题:
synchronized翻译过来是同步的意思.synchronized(Object){…}方法使多用户同步共享同一个对象。Object表示被共享的对象,{}中包含对该对象进行操作的代码。当被共享的对象正在被使用时,其他的用户只能等待,直到上一个用户对其操作结束。
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>使用request对象获取请求参数值</title>
</head>
<body><style background="green"></style>
<%
int i = 0;
synchronized (application) {
if (application.getAttribute("times") == null) { //服务器启动后的第一位访问者
i = 1;
} else {
i = Integer.parseInt((String) application.getAttribute("times"));
i++; //访问次数加1
}
application.setAttribute("times", Integer.toString(i)); //将访问次数存入Application对象中
}
%>
<table>
<tr bgcolor="lightgrey">
<td align="center">欢迎访问!</td>
</tr>
<tr>
<td align="center">您是第<b><%=i%></b>位访问本网站的游客!
</td>
</tr>
</table>
</body>
</html>