2.5 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 100以内的素数

100以内的素数

<% int count = 0; out.print("

"); for (int i = 2; i <= 100; i++) { boolean isPrime = true; if (i <= 1) { isPrime = false; } else if (i == 2) { isPrime = true; } else if (i % 2 == 0) { isPrime = false; } else { for (int j = 3; j <= Math.sqrt(i); j += 2) { if (i % j == 0) { isPrime = false; break; } } } if (isPrime) { out.print(i + " "); count++; } } out.print("

"); out.print("

总共找到 " + count + " 个素数

"); %> 2.4 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 页面计数器

页面访问计数器

<% // 获取application中的计数器 Integer count = (Integer) application.getAttribute("visitCount"); // 如果是第一次访问,初始化计数器 if (count == null) { count = 0; } // 检查session中是否有标记,判断是否是新的访问 Boolean visited = (Boolean) session.getAttribute("visited"); if (visited == null) { // 新访问,增加计数 count++; application.setAttribute("visitCount", count); session.setAttribute("visited", true); } // 显示计数结果 out.println("

当前页面访问次数: " + count + "

"); // 添加一个重置按钮(可选) if (request.getParameter("reset") != null) { application.setAttribute("visitCount", 0); session.removeAttribute("visited"); out.println("

计数器已重置

"); response.sendRedirect(request.getRequestURI()); } %>

重置计数器

刷新页面