Article Directory
First, the idea
(A) the variable (hitcounter) is effective during operation of the program, it will not be reset. Therefore, using the scope's largest application built-in objects.
(B) obtain application already exists (may not exist).
Integer hitCounter = (Integer)application.getAttribute("hitCounter");
(C) whether judgment already exists.
project | does not exist | presence |
---|---|---|
condition | hitCounter == null || hitCounter == 0。 | hitCounter != null && hitCounter != 0 |
deal with | hitCounter = 1 | hitCounter++ |
(D) the updated data, and then re-write the program.
application.setAttribute("hitCounter", hitCounter);
(E) page displays.
<p>页面访问量为: <%=hitCounter %></p>
Second, short-term memory (no database)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>访问量统计</title>
</head>
<body>
<%
Integer hitsCount = (Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ){
out.println("欢迎访问!");
hitsCount = 1; /* 第一次访问 */
}else{
out.println("欢迎再次访问!");
hitsCount += 1;/* 返回访问值 */
}
application.setAttribute("hitCounter", hitsCount);
%>
<p>页面访问量为: <%=hitsCount %></p>
</body>
</html>
Third, the long-term storage (with database)
The need to constantly connect to the database, poor performance. ... unfinished.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>访问量统计</title>
</head>
<body>
<%
Integer hitsCount = (Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ){
out.println("欢迎访问!");
hitsCount = 1; /* 第一次访问 */
}else{
out.println("欢迎再次访问!");
hitsCount += 1;/* 返回访问值 */
}
application.setAttribute("hitCounter", hitsCount);
%>
<p>页面访问量为: <%=hitsCount %></p>
</body>
</html>