protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext application = this.getServletContext();
Integer count = (Integer) application.getAttribute("count");
System.out.println("top:"+count);
if(count==null){
application.setAttribute("count", 1);
System.out.println("if:"+count);
}else{
application.setAttribute("count", count++);
System.out.println("else:"+count);
}
System.out.println("bottom:"+count);
PrintWriter pw = response.getWriter();
pw.print("<h1>"+count+"</h1>");
}
这时候刷新浏览器首先是null,再次刷新就是2,然后再刷新也没有变化,一直是2(有时候有其他成功的案例使浏览器有缓存时,可能会正常增加)
问题原因:
出现null的原因:if判断后只是将ServletContext的count的值变成1,但是我们自己定义的count没有变化还是null,所以在最后输出流输出的时候就是null
直接变成2 的原因:ServletContext的count第一次访问之后就是1了,再次访问的时候将1赋值给我们的count,再次判断 走else分支,count++先赋值,后自加。所以ServletContext的count的值还是1,但是我们的count就是2.。。。
解决:
if语句判断之后 给我们的count赋值为1
另外将else的count++改为++count或者是count+1
public class BServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext application = this.getServletContext();
Integer count = (Integer) application.getAttribute("count");
System.out.println("top:"+count);
if(count==null){
application.setAttribute("count", 1);
count = 1;
System.out.println("if:"+count);
}else{
application.setAttribute("count", count+1);
System.out.println("else:"+count);
}
System.out.println("bottom:"+count);
PrintWriter pw = response.getWriter();
pw.print("<h1>"+count+"</h1>");
}
}