这篇文章将为大家详细讲解有关利用servlet如何实现一个监听在线人数功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
公司主营业务:做网站、成都网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联公司推出雁江免费做网站回馈大家。
具体内容如下
ServletContext事件监听器---->针对applicationScope
ServletContextListener(*)
对整个Web应用的装载和卸载进行监听。
ServletContextAttributeListener
对ServletContext中的信息存放、删除和替换进行监听。
ServletContext就是Servlet上下文监听,在web中表示的是对启动服务和销毁服务进行监听,需要实现的接口:
ServletContextListener接口,实现的就是对上下午进行监听:
void contextInitialized(ServletContextEvent sce):启动上下文时的监听
void contextDestroyed(ServletContextEvent sce):销毁上下文时进行的监听
除了对上下文的启动和销毁进行监听的之外,还可以对上下文的属性进行监听:ServletContextAttributeListener接口。
void attributeAdded(ServletContextAttributeEvent event):设置上下文属性监听
void attributeRemoved(ServletContextAttributeEvent event):移除上下文属性的监听
void attributeReplaced(ServletContextAttributeEvent event):修改上下文属性的监听
ServletContextAttributeEvent:事件,可以通过事件取得属性的内容和名称。
·取得属性名称:public java.lang.String getName()
·取得属性的值:public java.lang.Object getValue()
效果如下图:
当登录一个账号时
打开另一个浏览器,再登录一个账号
如上图,我们可以看到,程序已经完成了统计在线人数和显示人员列表的功能,那么他的实现流程是什么呢?
我们可以通过ServletContextListener完成在线人数的统计和显示在线人数列表,首先listener和filter一样要在web.xml中进行描述。
代码如下:
net.jvsun.ListenerTest
为了测试这个程序,我们也必须完成用户登录功能。
数据库连接帮助类:
public class JDBCHelper { public static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String URL = "jdbc:oracle:thin:@localhost:1521:xxx"; public static final String DBNAME = "scott"; public static final String PASSWORD = "xxx"; public static Connection getConn() throws Exception{ Class.forName(DRIVER); Connection conn = DriverManager.getConnection(URL, DBNAME, PASSWORD); return conn; } }
用户实体类:
public class UserPOJO implements Serializable{ private static final long serialVersionUID = 7554548269035753256L; private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public UserPOJO(int id, String username, String password) { super(); this.id = id; this.username = username; this.password = password; } public UserPOJO(String username, String password) { this.username = username; this.password = password; } public UserPOJO() { super(); // TODO Auto-generated constructor stub } }
数据库处理类:
public class UserDAO { public UserPOJO login(String username, String password) { UserPOJO user=null; Connection conn = null; PreparedStatement pstate = null; ResultSet res = null; try { conn=JDBCHelper.getConn(); String sql="select id,username from userinfo where username=? and password=?"; pstate = conn.prepareStatement(sql); pstate.setString(1, username); pstate.setString(2, password); res = pstate.executeQuery(); while(res.next()){ user=new UserPOJO(res.getInt(1),username,null); } } catch (Exception e) { e.printStackTrace(); }finally{ try { res.close(); pstate.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return user; } }
servlet类:
public class UserServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getContextPath(); response.setContentType("text/html; charset=utf-8"); request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); ServletContext application = this.getServletContext();//取得application对象 Listlist = (List ) application.getAttribute("allUser"); if(list.indexOf(username) == -1){ UserPOJO pojo = new UserDAO().login(username, password); if(null != pojo){ HttpSession session = request.getSession(true);//取得session对象 session.setAttribute("userName", username); } } response.sendRedirect(path+"/index.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
监听类:
public class ListenerTest implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener{ ServletContext application = null; public void contextDestroyed(ServletContextEvent event) { System.out.println("服务器关闭"); } public void contextInitialized(ServletContextEvent event) { Listlist = new ArrayList (); //用来保存所有已登录的用户 application = event.getServletContext(); //取得application对象 application.setAttribute("allUser", list); //将集合设置到application范围属性中去 } public void attributeAdded(HttpSessionBindingEvent se) { List list = (List )application.getAttribute("allUser"); //假设:用户登陆成功之后,只将户名设置到session中 String userName = (String)se.getValue(); //取得用户名 if(list.indexOf(userName) == -1){ //表示此用户之前没有登陆 list.add(userName); application.setAttribute("allUser", list); } } public void attributeRemoved(HttpSessionBindingEvent se) { List list = (List )application.getAttribute("allUser"); list.remove((String)se.getValue()); application.setAttribute("allUser", list); } public void attributeReplaced(HttpSessionBindingEvent se) { } public void sessionCreated(HttpSessionEvent event) { } public void sessionDestroyed(HttpSessionEvent event) { } }
登录页面
<%@page contentType="text/html; charset=utf-8"%> <%@page import="java.util.*" %> <% String path = request.getContextPath(); %>
显示在线人数和在线人员的列表界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
注销界面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>logout <% session.removeAttribute("username"); session.invalidate(); response.sendRedirect("login.jsp"); %>
关于利用servlet如何实现一个监听在线人数功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。