ServletContext对象统计在线人数
Posted 初夏的一棵歪脖子树
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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=(Integer)context.getAttribute("count"); //定义访问人数变量 int count=1; if(value==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); } }
通过此路径在浏览器上访问 http://localhost:8080/webProject1/CountVisited
以上是关于ServletContext对象统计在线人数的主要内容,如果未能解决你的问题,请参考以下文章