Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีทำ Hit Counter ใน JSP

Hit counter นับจำนวนเข้าชมหน้าเว็บ ใช้ application implicit object (ServletContext)

เมธอดหลัก

  • application.setAttribute(key, value) - เซตค่า
  • application.getAttribute(key) - อ่านค่า

Application object มีชีวิตตลอด webapp (สร้างตอน deploy, หายตอน undeploy)

ตัวอย่าง main.jsp

<%@ page import="java.io.*,java.util.*" %>
<html>
<head><title>Hit Counter</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++;
        }
        application.setAttribute("hitCounter", hitsCount);
    %>
    <center>
        <p>Total visits: <%= hitsCount %></p>
    </center>
</body>
</html>

ผลลัพธ์

Welcome back to my website!
Total number of visits: 12

การทดสอบ

  1. วาง main.jsp ใน <Tomcat>/webapps/ROOT/
  2. 2. เปิด https://localhost:8080/main.jsp 3. Refresh (F5) หลายครั้ง → จำนวนเพิ่มขึ้น 4. เปิด browser คนละตัว → counter รวม (shared application scope)

ขยาย: Counter ทั้งเว็บไซต์

Include โค้ดนี้ในทุก JSP (หรือ dùng Filter/Listener)

ข้อจำกัด

  • Reset เมื่อ restart server (ดูแก้ใน ID 1004075961)
  • Clustered environment: ต้องใช้ shared store (DB, Redis)
  • Race condition: ใช้ AtomicInteger หรือ synchronized block

Thread-Safe Version

<%
    synchronized (application) {
        Integer count = (Integer) application.getAttribute("hitCounter");
        count = (count == null) ? 1 : count + 1;
        application.setAttribute("hitCounter", count);
        out.println("Visits: " + count);
    }
%>