Hit Counter

PHOTO EMBED

Fri Nov 15 2024 15:17:11 GMT+0000 (Coordinated Universal Time)

Saved by @signup_returns

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
import jakarta.servlet.annotation.*;

@WebServlet("/hitcounter")
public class HitCounterServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set the content type to HTML
        response.setContentType("text/html");

        // Get the writer to send the response
        PrintWriter out = response.getWriter();

        // Get the cookies from the request
        Cookie[] cookies = request.getCookies();
        int hitCount = 0;

        // Check if there's a cookie for 'hitCount'
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("hitCount".equals(cookie.getName())) {
                    hitCount = Integer.parseInt(cookie.getValue());
                    break;
                }
            }
        }

        // Increment the hit count
        hitCount++;

        // Create or update the 'hitCount' cookie
        Cookie hitCountCookie = new Cookie("hitCount", String.valueOf(hitCount));
        hitCountCookie.setMaxAge(60 * 60 * 24 * 7); // 1 week expiry time
        response.addCookie(hitCountCookie);

        // Generate the HTML response
        out.println("<html>");
        out.println("<head><title>Hit Counter</title></head>");
        out.println("<body>");
        out.println("<h1>Page hit count: " + hitCount + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}
content_copyCOPY