在本章中,我们将在jsp中讨论如何实现点击量统计。 点击计数器用于统计有关网站的特定页面上的访问次数。假设人们首先登陆网站主页,通常是index.jsp页面中有点击计数器。
要实现一个点击计数器,可使用application隐式对象和关联的getattribute()和setattribute()方法。
该对象是jsp页面在其整个生命周期中的表示。 当jsp页面被初始化时,将创建此对象,并且在jsp页面被jspdestroy()方法删除时将被删除。
以下是在应用程序级别设置变量的语法 -
application.setattribute(string key, object value);
可以使用上述方法设置命中计数器变量并重置相同的变量。以下是读取以前方法设置的变量的方法 -
application.getattribute(string key);
每当用户访问页面时,可以读取点击计数器的当前值并将其添加1,并再次设置它以供将来使用。
示例
此示例显示如何使用jsp来计算特定页面上的匹配总数。如果想计算网站的总点击次数,那么需要在所有jsp页面中包含相同的代码。
打开 eclipse 创建一个动态web项目:hitscounter ,其项目中的jsp文件如下所示 -
文件:index.jsp -
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>页面点击统计</title>
</head>
<body>
<div style="margin: auto; width: 80%">
<%
integer hitscount = (integer) application.getattribute("hitcounter");
if (hitscount == null || hitscount == 0) {
/* first visit */
out.println("欢迎您来到我的网站!");
hitscount = 1;
} else {
/* return visit */
out.println("欢迎您再次访问我的网站!");
hitscount += 1;
}
application.setattribute("hitcounter", hitscount);
%>
<center>
<p>
访问总数:<%=hitscount%></p>
</center>
</div>
</body>
</html> 在编写完成以上代码后,部署项目并访问以下url: http://localhost:8080/hitscounter/index.jsp ,应该会看到以下结果 -
再次刷新上面的网址,应该会看到以下结果-
复制以上index.jsp中的代码,放到另一个jsp文件:index2.jsp文件中,然后访问: http://localhost:8080/hitscounter/index2.jsp ,应该会看到以下结果 -
可以看到访问总数为:3
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!