Servlet编写计算网页计数器问题哭求各位高手请教啊!

来源:百度知道 编辑:UC知道 时间:2024/06/15 21:42:02
在doGet内写的代码
int i=0;
Integer num=new Integer(0);
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();

ServletContext context=this.getServletContext();
num=(Integer)context.getAttribute("count");
if(num==null)
{
i=1;
num=new Integer(1);

}
else
{
i=num.intValue()+1;
num=new Integer(num.intValue()+1);
}
context.setAttribute("count",num);
out.println("<html>");
out.println("<head><title>Servlet1</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>您已经访问了"+i+"次</p>");
out.println("</body>");

JSP实现的,我已经测试过,正确:
<%@ page contentType= "text/html;charset=GBK" language= "java"%>
<%
Integer count=null;
synchronized(application){
count=(Integer)application.getAttribute("basic.counter");
if(count==null)
count=new Integer(0);
count=new Integer(count.intValue()+1);
application.setAttribute("basic.counter",count);
}
%>
<html>
<head><title>counter.jsp</title></head>
<body bgcolor=#ffffff>
<h1>访问次数:<%=count%></h1>
</body>
</html>