当Web服务器启动时,Web服务器会自动创建一个application对象。application对象一旦创建,它将一直存在,直到Web服务器关闭才消失。我们就可以利用这个特性来记录网页刷新的次数。
1.首先在webapp文件夹下创建一个名为index的JSP
如图所示:

2.接下来就是写代码了
index.jsp的代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Object count =application.getAttribute("count");
if(count==null){
//application中未存放count
application.setAttribute("count",new Integer(1));
}else{
//application中已存放count
Integer i=(Integer)count;
application.setAttribute("count",i.intValue()+1);
}
Integer sount=(Integer)application.getAttribute("count");
%>
<h2>Hello World!<

本文介绍了如何在Java Web中利用application对象持久化记录网页刷新次数。通过创建JSP页面并编写代码,每次刷新页面时,application对象的计数器都会增加,展示了Web服务器启动到关闭期间application对象的生命周期。
最低0.47元/天 解锁文章
171万+





