JSP计数器--网站统计访问量

时间:2021-11-06 14:50:09
<span style="font-family:Arial;">第一种直接用jsp的内置对象</span>
<body><%Integer count = (Integer) application.getAttribute("counter");if(count == null){count=0;}//计数器加1count++;//写入计数器application.setAttribute("counter", count);%><h1>计数器</h1>你是第<%=count %>位访问者</body>


第二种:用ServletContext(但我们推荐用第一种)

package 网站统计访问量;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CountServlet")
public class CountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
ServletContext application = request.getServletContext();
Integer count = (Integer) application.getAttribute("counter");
/*
* 1. 获取ServletContext对象 2. 从ServletContext对象中获取名为count的属性 3.
* 如果存在:给访问量加1,然后再保存回去; 4.
* 如果不存在:说明是第一次访问,向Servletcontext中保存名为count的属性,值为1
*/
//下面注释的部分有点错误,在第一次访问的时候会输出null,所以最好用第二种
//if (count == null) {
//application.setAttribute("counter", 1);
//} else {
//application.setAttribute("counter", count + 1);// 每访问一次加1
//}
if(count == null){
count=0;
}
count++;
application.setAttribute("counter", count);

System.out.println("访问量:" + count);// 是在控制台输出
/*
* 向浏览器输出 需要使用响应对象!
*/
PrintWriter out = response.getWriter();
out.print("访问量" + "<h2>" + count + "</h2>");//在浏览器页面输出
}

}