+ -
当前位置:首页 → 问答吧 → jsp开发简单计数器的问题

jsp开发简单计数器的问题

时间:2011-08-27

来源:互联网

<%
int count = 0;

if(application.getAttribute("count") == null) {
++count;
application.setAttribute("count", count);
}
else {
count = Integer.parseInt(application.getAttribute("count").toString());
++count;
application.setAttribute("count", count);
}

out.println("这是您第" + count + "次访问本服务器");
%>


若去掉count = Integer.parseInt(application.getAttribute("count").toString());这一行为什么不能累加?

作者: qweorou   发布时间: 2011-08-27

还有,count=0即application.getAttribute("count")==null的意思吗?

作者: qweorou   发布时间: 2011-08-27

如果去掉那行
不是不能累加。已经累加了 。只是你没有把累加后的结果再赋给count而已。
就像没有刷新一样。
所以显示的count一直没有变。

作者: is_zhoufeng   发布时间: 2011-08-27

++count它会去找最近的count,
如果你去掉了count = Integer.parseInt(application.getAttribute("count").toString());
所以它每次都去找int count = 0;
那么执行完++count后
打印出来的值每次都是1

作者: k3108001263   发布时间: 2011-08-27

application.getAttribute("count")==null表示aplication里面还没有设置key为count的键

count = 0 不等于 count = null

<%
int count = 0;

if(application.getAttribute("count") == null) {
++count;
application.setAttribute("count", count);
}

这个if语句里面的意思为:如果application里面如果没有键为count的key。那么就将count++ ,也就是count等于1了。 然后将count设置到application里面。

作者: is_zhoufeng   发布时间: 2011-08-27

引用 1 楼 qweorou 的回复:

还有,count=0即application.getAttribute("count")==null的意思吗?


你要先了解内置对象和作用域有哪些,功能分别有什么?如何使用?
http://blog.csdn.net/DL88250/article/details/1875298

作者: k3108001263   发布时间: 2011-08-27

那么其实不用那么麻烦吧,直接:
<%
int count = 0;


count = Integer.parseInt(application.getAttribute("count").toString());
++count;
application.setAttribute("count", count);


out.println("这是您第" + count + "次访问本服务器");
%>

这样不就可以了嘛。。。。不过我想问一下有判断语句那个和这个没有判断语句的到底谁更好?

作者: qweorou   发布时间: 2011-08-27

其实为什么多了count = Integer.parseInt(application.getAttribute("count").toString());这一句就会刷新增量;而没有这一句就不增量呢?按道理应该结果都一样吧。。。因为每刷新一次都会执行int count = 0;的,即每一次都重新计数的不是吗?

作者: qweorou   发布时间: 2011-08-27

<%
int count = 0;


count = Integer.parseInt(application.getAttribute("count").toString());
++count;
application.setAttribute("count", count);


out.println("这是您第" + count + "次访问本服务器");
%>

为什么这个程序有时会出错,有时不会出错呢??真叫人心烦

作者: qweorou   发布时间: 2011-08-27