这篇文章是关于如何用监听器实现计数器的,下图是建好的样子,只用建你能看到的。
如果已经生成了web.xml文件就不用再建了,把其他的建好,代码放进去。运行失败的话,再改web.xml的代码。
counter1.jsp
<%@ page contentType="text/html; charset=gb2312" language="java" errorPage="" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>计数器</title>
</head>
<body>
<%
int number=0;
if(application.getAttribute("number")==null){
number=1;
}else{
number=Integer.parseInt((String)application.getAttribute("number"));
number=number+1;
}
out.print("您是第"+number+"位访问者!");
application.setAttribute("number",String.valueOf(number));
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Experiments</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行结果