当前位置: 代码迷 >> Java Web开发 >> 对Servlet中的ServletContext一个疑义,求解释
  详细解决方案

对Servlet中的ServletContext一个疑义,求解释

热度:80   发布时间:2016-04-16 22:00:55.0
对Servlet中的ServletContext一个疑问,求解释!
用ServletContext获得访问次数,就自加在前和在后,居然得出来的不一样。迷惑了……

ServletContext application = this.getServletContext();
Integer count = (Integer) application.getAttribute("count");
if (count == null)
    application.setAttribute("count", 1);
else {
    application.setAttribute("count", count++); //注意count++,++在后面
}
Integer i = count;
pw.print("<br />访问次数:" + i);


count++按理说没问题吧,但是当加到2的时候,下次再访问,Integer count = (Integer) application.getAttribute("count");得出来的居然成1了。而如果++count这样写,却正常。不解啊!
------解决方案--------------------
++count在前面,每次存的时候是 count=count+1;都是加了1之后赋值的,count++是 先用的是 count=count; 后 count+1;的
所以count++存的时候每次都是   1
------解决方案--------------------
if (count == null)
    application.setAttribute("count", 1);
else {
count++;
    application.setAttribute("count", count); 
}

这样就跟  ++count 的一样了
------解决方案--------------------
if (count == null)
    application.setAttribute("count", 1);
else {
    application.setAttribute("count", count++); //注意count++,++在后面
}

当进入到else代码块时,count++ 是在 application.setAttribute("count", count++); 这条语句执行完之后再加1的,所以你先把它存到application中了,然后才加1,所以每次都会是1咯。建议你像楼上那样写吧。逻辑也会清晰一点。
  相关解决方案