使用java中的session来记录访问次数
<%@ page import="java.net.CookieHandler" %><%-- Created by IntelliJ IDEA. User: DELL Date: 2018/4/19 Time: 17:06 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="java.net.*,java.util.*,java.io.*" %> <html> <head> <title>Title</title> </head> <body> <% //session //获取session创建的时间 Date createTime = new Date(session.getCreationTime()); //获取最后访问页面的时间 Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "再次访问"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // 检测网页是否由新的访问用户 if (session.isNew()) { title = "访问"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } else { visitCount = (Integer) session.getAttribute(visitCountKey); visitCount += 1; userID = (String) session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); if (visitCount >= 2) { // session.removeAttribute(userIDKey); //销毁session,清零; session.invalidate(); } } %> <h1>设置Cookie</h1> <ul> <li>名称:<%= request.getParameter("userName")%> </li> <li>url:<%= request.getParameter("url")%> </li> </ul> <h2>session</h2> <table border="1" align="center"> <tr bgcolor="#949494"> <th>Session 信息</th> <th>值</th> </tr> <tr> <td>id</td> <td><% out.print(session.getId()); %></td> </tr> <tr> <td>创建时间</td> <td><% out.print(createTime); %></td> </tr> <tr> <td>最后访问时间</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>用户 ID</td> <td><% out.print(userID); %></td> </tr> <tr> <td>访问次数</td> <td><% out.print(visitCount); %></td> </tr> </table> <%--</script>--%> </html>
在这里博主做了一个小小的判断,当访问次数大于等于2的时候,session会销毁然后进行清零重新计算。