1. 程式人生 > >Java Web統計站點訪問次數並記錄訪問者的IP

Java Web統計站點訪問次數並記錄訪問者的IP

<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.HashSet" %>
<%@ page import="util.NetWork" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
    <head>
        <title>訪問</title>
    </head>
    <body>
        <%
            String ip = new NetWork().getIP(request);
            Set<String> set = (Set<String>) application.getAttribute("ips");
            if (set == null) {
                set = new HashSet<>();
                /*application.setAttribute("ips", set);*/
            }
            set.add(ip);
            application.setAttribute("ips", set);
        %>
        <%String data = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());%>
        您是第<%=set.size()%>個訪問者,訪問IP為:<%=ip%>,本次訪問時間:<%=data%><br/>
        <%
            Integer sessionCount = (Integer) session.getAttribute("sessionCount");
            if (sessionCount == null) {
                sessionCount = 0;
            }
            sessionCount = sessionCount + 1;
            session.setAttribute("sessionCount", sessionCount);

            Integer applicationCount = (Integer) application.getAttribute("applicationCount");
            if (applicationCount == null) {
                applicationCount = 0;
            }
            applicationCount = applicationCount + 1;
            application.setAttribute("applicationCount", applicationCount);
        %>
        當前回話共訪問<%=sessionCount%>次,本站共訪問<%=applicationCount%>次
    </body>
</html>

Java Web獲取訪問者IP的方式參見另一篇部落格