Servlet中实现用servletContext对象统计网站在线人数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pangqiandou/article/details/53166626

1:servletContext

package com.study;


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


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


public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;




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


request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
ServletContext ctx=this.getServletContext();
synchronized(this)
{
Integer counter=(Integer)ctx.getAttribute("userNumber");
int temp=0;
if(counter==null)
counter=new Integer(1);
else
{
temp=counter.intValue()+1;
counter=new Integer(temp);
}
ctx.setAttribute("userNumber", temp);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML>");
out.println("<html>");
out.println("<head><title>login Servlet</title></head>");
out.println("<body>");
out.print("这是第一页<br/>");
out.print("<a href='UserNumberServlet'>人数统计</a>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();

}



public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


}


}


 2;统计在线人数

package com.study;


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


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


public class UserNumberServlet extends HttpServlet {


private static final long serialVersionUID = 1L;


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


request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext ctx=this.getServletContext();
Integer counter=(Integer)ctx.getAttribute("userNumber");
out.println("<!DOCTYPE HTML>");
out.println("<html>");
out.println("<head><title>统计在线人数</title></head>");
out.println("<body>");
if(counter==null)
out.print("恭喜您是第一个访问本网站的用户!");
else
out.print("已经有"+counter+"人在访问本网站");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();

}



public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {



}


}

阅读更多
换一批

没有更多推荐了,返回首页