java使用监听器实现一个统计网站在线人数的示例
本文主要介绍了java使用监听器实现一个统计网站在线人数的示例,具有一定的参考价值,有需要的朋友可以了解一下。
(1)创建一个监听器实现类
要大致统计一个网站的在线人数,首先,可以通过ServletContextListener监听,当Web应用上下文启动时,在ServletContext中添加一个List,用来准备存放在线的用户名;然后,可以通过HttpSessionAttributeListener监听,当用户登录成功把用户名设置到Session中时同时将用户名存放到ServletContext中的List列表中;最后通过HttpSessionListener监听,当用户注销会话时将用户名从应用上下文范围中的List列表中删除。
所以,编写OnLineListener类实现ServletContextListener、HttpSessionAttributeListener、HttpSessionListener接口,具体代码如下:
packagecom.web.servlet;
importJava.util.LinkedList;
importjava.util.List;
importjavax.servlet.ServletContext;
importjavax.servlet.ServletContextEvent;
importjavax.servlet.ServletContextListener;
importjavax.servlet.http.HttpSessionAttributeListener;
importjavax.servlet.http.HttpSessionBindingEvent;
importjavax.servlet.http.HttpSessionEvent;
importjavax.servlet.http.HttpSessionListener;
//在线人数统计监听器实现类
publicclassOnlineListenerimplementsServletContextListener,
HttpSessionAttributeListener,HttpSessionListener{
privateServletContextapplication=null;
publicvoidcontextDestroyed(ServletContextEventarg0){
//TODOAuto-generatedmethodstub
}
publicvoidcontextInitialized(ServletContextEventarg0){
//初始化一个application对象
this.application=arg0.getServletContext();
//设置一个列表属性,用于保存在想用户名
this.application.setAttribute("online",newLinkedList<String>());
}
//往会话中添加属性时会回调的方法
publicvoidattributeAdded(HttpSessionBindingEventarg0){
//取得用户名列表
List<String>online=(List<String>)this.application
.getAttribute("online");
if("username".equals(arg0.getName())){
//将当前用户名添加到列表中
online.add((String)arg0.getValue());
}
//将添加后的列表重新设置到application属性中
this.application.setAttribute("online",online);
}
publicvoidattributeRemoved(HttpSessionBindingEventarg0){
//TODOAuto-generatedmethodstub
}
publicvoidattributeReplaced(HttpSessionBindingEventarg0){
//TODOAuto-generatedmethodstub
}
publicvoidsessionCreated(HttpSessionEventarg0){
//TODOAuto-generatedmethodstub
}
//会话销毁时会回调的方法
publicvoidsessionDestroyed(HttpSessionEventarg0){
//取得用户名列表
List<String>online=(List<String>)this.application
.getAttribute("online");
//取得当前用户名
Stringusername=(String)arg0.getSession().getAttribute("username");
//将此用户名从列表中删除
online.remove(username);
//将删除后的列表重新设置到application属性中
this.application.setAttribute("online",online);
}
}
(2)在web.xml中注册监听器
监听器实现好后,还需要在web.xml文件中进行注册才能起作用,只需要在web.xml中像如下添加元素即可
<!--注册一个监听器--> <listener> <!--指定监听器实现类的全限定名--> <listener-class> com.web.servlet.OnlineListener </listener-class> </listener
最后,我们创建几个Servlet来测试这个监听器实现的功能。
处理用户登录的Servlet类代码:
packagecom.web.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
//处理用户登录的Servlet
publicclassLoginServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
this.doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
request.setCharacterEncoding("utf-8");//设置相应内容类型
Stringusername=request.getParameter("username");//获取请求参数中的用户名
//往session中添加属性,会触发HttpSessionAttributeListener中的attributeAdded方法
if(username!=null&&!username.equals("")){
request.getSession().setAttribute("username",username);
}
//从应用上下文中获取在线用户名列表
List<String>online=(List<String>)getServletContext().getAttribute("online");
response.setContentType("text/html;charset=utf-8");
PrintWriterout=response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>用户列表</TITLE></HEAD>");
out.println("<BODY>");
out.println("当前用户是:"+username);
out.print("<hr/><h3>在线用户列表</h3>");
intsize=online==null?0:online.size();
for(inti=0;i<size;i++){
if(i>0){
out.println("<br/>");
}
out.println(i+1+"."+online.get(i));
}
//注意:要对链接URL进行自动重写处理
out.println("<hr/><ahref="/"mce_href="/"""+response.encodeURL("logout")+"/">注销</a>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
处理用户登录Servlet的类代码
packagecom.web.servlet;
importjava.io.*;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.*;
//处理用户注销会话的Servlet
publicclassLogoutServletextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
this.doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
request.setCharacterEncoding("utf-8");
//销毁会话,会触发SessionLinstener中的sessionDestroyed方法
request.getSession().invalidate();
//从应用上下文中获取在线用户名列表
List<String>online=(List<String>)getServletContext().getAttribute("online");
response.setContentType("text/html;charset=utf-8");
PrintWriterout=response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>用户列表</TITLE></HEAD>");
out.println("<BODY>");
out.print("<h3>在线用户列表</h3>");
intsize=online==null?0:online.size();
for(inti=0;i<size;i++){
if(i>0){
out.println("<br/>");
}
out.println(i+1+"."+online.get(i));
}
out.println("<hr/><ahref="/"mce_href="/""index.html/">主页</a>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
然后创建一个index.html文件,用来供用户登录,代码如下:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <metahttp-equiv="content-type"content="text/html;charset=UTF-8"> <title>index.html</title> </head> <body> <formaction="login"method="post"> 用户名:<inputtype="text"name="username"/> <inputtype="submit"value="登录"/><br/><br/> </form> </body> </html>
把WEB部署到Tomcat容器总,并启动。打开浏览器访问即可
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。