jsp 如何实现网站的计数器功能
利用application对象和session对象实现网站的计数器功能。
application为所有用户共享,session单用户;application保存计数值,当session新建时加1.
index.jsp
[code]
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<%!
synchronized void count() {
ServletContext application = getServletContext();
Integer num = (Integer)application.getAttribute("num");
if (null == num) {
num = new Integer(1);
application.setAttribute("num", num);
} else {
num = new Integer(1 + num);
application.setAttribute("num", num);
}
}
%>
<%
if (session.isNew()) { //为了避免用户的刷新的问题
count();
}
Integer tNum = (Integer)application.getAttribute("num");
%>
欢迎访问,您是第<%=tNum %>个访问的用户!
</body>
</html>
[/code]
利用application对象和session对象实现网站的计数器功能。
application为所有用户共享,session单用户;application保存计数值,当session新建时加1.
index.jsp
[code]
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<%!
synchronized void count() {
ServletContext application = getServletContext();
Integer num = (Integer)application.getAttribute("num");
if (null == num) {
num = new Integer(1);
application.setAttribute("num", num);
} else {
num = new Integer(1 + num);
application.setAttribute("num", num);
}
}
%>
<%
if (session.isNew()) { //为了避免用户的刷新的问题
count();
}
Integer tNum = (Integer)application.getAttribute("num");
%>
欢迎访问,您是第<%=tNum %>个访问的用户!
</body>
</html>
[/code]