首页 > 代码库 > ServletContext对象统计在线人数

ServletContext对象统计在线人数

技术分享
package com.zdsofe.servlet1;

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;

/**
 * Servlet implementation class CountVisited
 */
@WebServlet("/CountVisited")
public class CountVisited extends HttpServlet {
    private static final long serialVersionUID = 1L;
  
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //编码格式
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //输出流
        PrintWriter out=response.getWriter();
        //获得上下文环境
        ServletContext context=    request.getServletContext();
        //获取访问人数
        Integer value=http://www.mamicode.com/(Integer)context.getAttribute("count");
        //定义访问人数变量
        int count=1;
        if(value=http://www.mamicode.com/=null)
        {
            out.write("你是第一个访问者");
        }
        else
        {
            count+=value;
        }
        context.setAttribute("count", count);
        //统计人数
        out.print(count);
        //刷新流
        out.flush();
        //关闭流
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
View Code

通过此路径在浏览器上访问  http://localhost:8080/webProject1/CountVisited

ServletContext对象统计在线人数