首页 > 代码库 > 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); } }
通过此路径在浏览器上访问 http://localhost:8080/webProject1/CountVisited
ServletContext对象统计在线人数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。