Context对象中,统计访问次数,这个域范围是Application,即关闭服务器,才会停止计数,但有缺点,即没个用户存进去都是一样的,往一个池子里塞东西,以后运用到Session计数,即可完成一次会话计数,即浏览器关闭,重新计数,符合企业要求。
package com.ljy.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class ServletContext extends HttpServlet {
@Override
public void init() throws ServletException {
javax.servlet.ServletContext context = super.getServletContext();
context.setAttribute("count",0);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//统计次数
javax.servlet.ServletContext context = super.getServletContext();
Integer count = (Integer)context.getAttribute("count");
count++;
System.out.println("Welcome"+count);
context.setAttribute("count",count);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}