Hit counter cho biết số lượt truy cập trang web. Thường gắn vào index.jsp (trang chủ).
Dùng Application Implicit object với getAttribute() và setAttribute().
Đối tượng này đại diện JSP suốt vòng đời. Tạo khi JSP khởi tạo, xóa khi jspDestroy().
Cú pháp
Set biến mức application:
application.setAttribute(String Key, Object Value);
Đọc biến:
application.getAttribute(String Key);
Mỗi lần truy cập, đọc hit counter, tăng 1, set lại.
Ví dụ
<%@ page import = "java.io.*,java.util.*" %>
<html>
<head> <title>Application object in JSP</title> </head>
<body>
<%
Integer hitsCount = (Integer)application.getAttribute("hitCounter");
if (hitsCount == null || hitsCount == 0) {
out.println("Welcome to my website!");
hitsCount = 1;
} else {
out.println("Welcome back to my website!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<center> <p>Total number of visits: <%= hitsCount %></p> </center>
</body>
</html>
Đặt vào main.jsp, gọi https://localhost:8080/main.jsp. Giá trị tăng mỗi lần refresh. Thử browser khác, counter vẫn tăng.
Kết quả
Welcome back to my website! Total number of visits: 12