[JSP] 利用application来写一个网页计数器

利用application写一个网页计数器

实现这一应用, 要用到application下面的两个方法:

application.setAttribute() 和 application.getAttribute()

代码如下:

View Code
<%-- 
Document : count
Created
on : Jul 28, 2011, 10:38:56 PM
Author : shy
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>网页计数器</title>
</head>
<body>
<h1>网页计数器</h1>

<%
/*
*判断之前是否有用application设置过Attribute
*如果没有设置过,就将其值设置为 1
*如果有设置过, 就用getAttribute()方法得到它,当网页第次刷新时, 就让这个值自加 1
*然后再将这个值用setAttribtue()设置,供下次使用.
*/
if(application.getAttribute("count")==null){
application.setAttribute(
"count", "1");
}
else{
//将得到的对象转换成 字符串 形式
String strCount = application.getAttribute("count").toString();
//将字符串转换成 整形
int intCount =Integer.parseInt(strCount);
//让其进行自加1运算
intCount
++;
//再将自加后的变量设置给application
application.setAttribute(
"count", Integer.toString(intCount));
}
%>
<%--输出,只要服务器不关闭,第一次刷新网页, 显示的结果都会增加1--%>
你是第
<%=application.getAttribute("count") %>访问者!
</body>
</html>
posted @ 2011-07-28 23:10  ShanHaiyang  阅读(1503)  评论(3编辑  收藏  举报